Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用scanf读取字符串时程序崩溃_C++_Scanf - Fatal编程技术网

C++ 使用scanf读取字符串时程序崩溃

C++ 使用scanf读取字符串时程序崩溃,c++,scanf,C++,Scanf,我的程序总是在类函数的第5次扫描后崩溃 class PersoenlicheDaten{ public: void eingabe(){ printf("Bitte geben sie jetzt ihre Persoenlichen Daten ein: \n\n"); printf("Vorname: "); scanf("%s", &vorname); print

我的程序总是在类函数的第5次扫描后崩溃

class PersoenlicheDaten{
    public:
        void eingabe(){
            printf("Bitte geben sie jetzt ihre Persoenlichen Daten ein: \n\n");
            printf("Vorname: ");
            scanf("%s", &vorname);
            printf("Nachname: ");
            scanf("%s", &nachname);
            printf("Alter: ");
            scanf("%d", &alter);
            printf("Geburtsdatum: ");
            scanf("%s", &geburtsdatum);
            printf("Addresse: ");
            scanf("%s", &addresse);
        }
    private:
        std::string vorname;
        std::string nachname;
        int alter;
        std::string geburtsdatum;
        std::string addresse;
};
内部
main

do{
    pd.eingabe();
    printf("Sind sie mit der eingabe zufrieden?\n\n");
    printf("Antwort(j/n): ");
    scanf("%c", &v.antwiederholen);
    if(v.antwiederholen == 'j'){
        v.running = true;
    }else{
        v.running = false;
    }
}while(v.running);

为什么会这样,因为它应该正常工作。另外,我想使用scanf而不是std::cin来学习不同的输入方法。

这里的问题是,您不能使用
scanf
来读取
std::string
。您必须将
std::string
转换为
char*
,或者使用
cin
。您可以做的另一件事是,首先从scanf读取一个临时的
char*
,然后通过如下操作将其转换为
std::string

scanf("%s", &someCharPointer);
std::string s = someCharPointer;

作为评论,尝试学习如何使用不同的东西没有错。
scanf
cin
都有各自的优缺点。

要使用scanf读取字符串,实际上必须有足够大的缓冲区来读取字符串

char temp[100];
std::string vorname;
if(scanf("%99s", temp) ==1){
    vorname = temp;
}

使用scanf,您必须限制要读取的字符数,以匹配临时缓冲区,并在使用缓冲区读取之前检查返回值。当使用getline或operator>>从istream直接读取std::string时,字符串变量将增长以匹配用户输入

scanf
%s
采用
char*
,而不是
std::string*
if(COND){var=true;}否则{var=false;}最好写成
var=COND。切勿使用
scanf
进行用户输入。如果确实使用了
scanf
,请始终检查其返回值。
Persoenlichen
不应大写;这是个形容词。但是
eingabe
应该是因为它是一个名词。使用cin和cout。