我收到此錯誤字符串未聲明編譯此代碼時。編譯代碼時出錯
#include <stdio.h>
#include <stdlib.h>
int main()
{
string names;
printf("What is your name?\n");
scanf("%s", &names);
printf("Your name is %s", names);
return 0;
}
有人可以告訴我爲什麼。非常感謝
我收到此錯誤字符串未聲明編譯此代碼時。編譯代碼時出錯
#include <stdio.h>
#include <stdlib.h>
int main()
{
string names;
printf("What is your name?\n");
scanf("%s", &names);
printf("Your name is %s", names);
return 0;
}
有人可以告訴我爲什麼。非常感謝
你應該包括串標頭:
#include <string>
,並使用時,不要忘了命名空間std
:
std::string names;
此外,不要在混合C和C++代碼你。嘗試使用std::cout
而不是printf
,cin/getline
而不是scanf
。
特別是,將'std :: string'對象(本例中的名稱)作爲參數傳遞給'printf'肯定不會按預期工作。 –
@MatsPetersson這是我忽略的另一個重點。謝謝! – taocp
因爲std :: string是在頭文件字符串中定義的,而你沒有包含它,並且因爲它的完整名稱是std :: string,而不是字符串。
如果您正在編寫C++,那麼標準字符串類被稱爲std::string
,並且位於標頭<string>
中。但是,你通常不會想用printf
或scanf
有了它,你會使用C++ I/O:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string names;
cout << "What is your name?" << endl;
getline(cin, names);
cout << "Your name is " << names << endl;
}
如果(儘管問題標籤),你在寫C,那麼就沒有所謂的類型string
。字符串由字符數組常規表示:
char names[SOME_LARGE_NUMBER];
但要注意的是,除非你非常小心,scanf
可能使緩衝區溢出並導致運行時錯誤的所有方式。
您錯過了包含printf
和scanf
的定義的頭文件。將#include <string.h>
添加到代碼中。
此外,我認爲代碼在最後沒有return 0;
行。
包含'string'標頭。並像@taocp所說的那樣添加'std'。 –
另外,'printf'是一個C函數,它不知道流。使用'cin'和'cout'來代替舊的C函數。 – Wug
你使用哪種編譯器? – banuj