小编use*_*042的帖子

使用ifstream while循环,如何显示输入错误并在下一行继续?

如果我的输入文件以字母开头,它将停止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++ ifstream while-loop

0
推荐指数
1
解决办法
615
查看次数

如何使用C++在linux中创建一个空文件

我想用 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)

c++ fstream

-1
推荐指数
1
解决办法
1万
查看次数

找出{1,2,...,N}的排列数,使序列首先增加然后减少?

例如,对于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中遇到了这个问题,他们甚至没有为此提供社论.

algorithm math counting combinatorics

-1
推荐指数
1
解决办法
268
查看次数

根据标志运行两个不同的函数?

我正在编写一个程序,用户可以在开始时设置选项标志.

我的问题是我想根据用户标志调用不同版本的函数,我不想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)

c++ c++11 c++14

-1
推荐指数
1
解决办法
123
查看次数

C++:在"if语句"中的prim()

在研究B. Stroustrup 的C++编程语言时,已经提到了prim()函数的存在,它将声明的变量的范围缩小到一个单独的块.

这是本书提供的一个例子:

if (double d = prim(true)) {
        left /= d;      break;  
}
Run Code Online (Sandbox Code Playgroud)

尽管了解它的兴趣,但我无法弄清楚如何使用它:它是某个库的一部分吗?我必须精确标准,因为Visual Studio无法识别该功能.

提前致谢

c++ if-statement c++11

-2
推荐指数
1
解决办法
83
查看次数

我的程序没有打开文件中的数据.我没有错.我错过了重要的事吗?

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)

c++

-4
推荐指数
1
解决办法
50
查看次数

哪些是C++中条件(if)语句最常见的陷阱?

前言

这个问题是指使用类似if() ... else或类似条件语句的最常见(初学者)错误的规范集合.答案旨在描述运行时的意外行为,语法缺陷和误解

if(x) {}
else (y) {}
Run Code Online (Sandbox Code Playgroud)

不应该在这里解决.


解决了问题

c++

-8
推荐指数
2
解决办法
467
查看次数