Visual Studio无法运行C++代码(其他IDE可正常运行)
Visual Studio编译C++代码报错的解决方法
这段C++代码在OnlineGDB等在线IDE能正常运行,但在Visual Studio里编译会提示「There were build error」:
#include<iostream> #include<vector> using namespace std; main() { int x; char str[80]; cout << "Enter a number and a string:\n"; cin >> x; cin.getline(str, 80); //take a string cout << "You have entered:\n"; cout << x << endl; cout << str << endl; }
问题根源
Visual Studio采用的MSVC编译器对C++标准的检查更严格,代码存在两处不符合标准的写法:
main函数未指定返回类型:C++标准明确要求main函数必须返回int,代码里main()的旧式写法仅兼容部分宽松编译器,MSVC默认规则下会报错。- 多行字符串字面量写法不合法:原代码中字符串直接换行(未用转义符
\n或标准多行字符串语法),属于非标准扩展写法,MSVC不支持。
修复后的代码
#include<iostream> #include<vector> using namespace std; int main() { int x; char str[80]; cout << "Enter a number and a string:\n"; cin >> x; cin.ignore(); // 清除数字输入后残留的换行符,避免getline读空内容 cin.getline(str, 80); cout << "You have entered:\n"; cout << x << endl; cout << str << endl; return 0; }
额外提示
原代码还有逻辑缺陷:cin >> x读取数字后,输入缓冲区会残留换行符,直接调用cin.getline会把这个换行符当成空字符串读取。添加cin.ignore()可以跳过残留字符,保证能正确获取用户输入的字符串。
内容的提问来源于stack exchange,提问作者Huy Trần
相关产品推荐
相关产品推荐

