如果我的输入文件以字母开头,它将停止while循环,因为它无法重写int1,我知道但是我怎么能够检测到这一点并显示一条错误消息,说workinfile>>int1不起作用,然后继续循环?
cin>>filename;
ifstream workingfile(filename);
while (workingfile>>int1>>int2>>string1>>string2) {
cout<<int1<<int2<<string1<<string2<<endl;
linenumread++;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过,但它不起作用,任何帮助将不胜感激
while (workingfile>>int1>>int2>>string1>>string2) {
if(!(workingfile>>int1))
{
cout<<"Error first value is not an integer"<<endl;
continue;
}
cout<<int1<<int2<<string1<<string2<<endl;
linenumread++;
}
Run Code Online (Sandbox Code Playgroud)
还有可能检测它是否也停止读取字符串?
输入文件看起来像这样
10 10 ab bc
11 11 cd ef
a
12 12 gh hi
Run Code Online (Sandbox Code Playgroud)
我想检测何时遇到无效输入,显示错误消息,并继续文件中的下一行.
我想用 c++ 在 ubuntu 中创建一个空文件,我尝试了很多方法,但它一直失败并显示此错误
错误:没有与 'std::basic_ofstream::open(std::cxxll::...
我的代码:
ifstream f(saltFile.c_str());
if (f.good())
{
cout << saltFile + " file already existed" << endl;
}
else
{
ofstream file;
file.open (saltFile, ios::out);
cout << saltFile << " created!" << endl;
}
Run Code Online (Sandbox Code Playgroud) 例如,对于N = 3. 排列是:
[1,3,2]
[2,3,1]
Run Code Online (Sandbox Code Playgroud)
注意:[1,2,3]并且[3,2,1]在此处无效,因为[1,2,3]增加但不减少,反之亦然[3,2,1].
我在TCS CodeVita 2017中遇到了这个问题,他们甚至没有为此提供社论.
我正在编写一个程序,用户可以在开始时设置选项标志.
我的问题是我想根据用户标志调用不同版本的函数,我不想if(flag)每次选择调用哪个版本时都要这样做,因为我必须检查if()我处理的每一行的语句.
这是一个学校项目所以我试图找到最有效的方法来确定我想要调用哪个函数, and I readif()`语句在这里很昂贵.
那么有没有办法在开始时基本上说
if(flag)
// use this function the rest of the program
else
// use this other function for the rest of the program
Run Code Online (Sandbox Code Playgroud) 在研究B. Stroustrup 的C++编程语言时,已经提到了prim()函数的存在,它将声明的变量的范围缩小到一个单独的块.
这是本书提供的一个例子:
Run Code Online (Sandbox Code Playgroud)if (double d = prim(true)) { left /= d; break; }
尽管了解它的兴趣,但我无法弄清楚如何使用它:它是某个库的一部分吗?我必须精确标准,因为Visual Studio无法识别该功能.
提前致谢
inputFile.open("V:\CmpSci201\Labs\PlayerStats.txt");
cout << "2017 Baseball Stats\n";
if (inputFile)
{
getline(inputFile, stats);
while (inputFile >> stats)
{
// ...
inputFile.close();
}
else
{
cout << "Error Opening the file.\n";
}
// ...
Run Code Online (Sandbox Code Playgroud) 前言
这个问题是指使用类似if() ... else或类似条件语句的最常见(初学者)错误的规范集合.答案旨在描述运行时的意外行为,语法缺陷和误解
Run Code Online (Sandbox Code Playgroud)if(x) {} else (y) {}
不应该在这里解决.
c++ ×6
c++11 ×2
algorithm ×1
c++14 ×1
counting ×1
fstream ×1
if-statement ×1
ifstream ×1
math ×1
while-loop ×1