【问题标题】:Read number from text file in C++从 C++ 中的文本文件中读取数字
【发布时间】:2020-08-16 23:09:48
【问题描述】:

我目前正在编写一个从 .txt 文件中读取数字的程序,但我需要它在文件中读取停止后中断循环

我知道这个while 声明是错误的,但我这正是我想要完成的。

while (inFile >> x && x != stop)
{
  //the basic adding up of the numbers
  sum = sum + x;
  cout<<sum<<endl;
  sum = x;
}

if (x == stop)
{
    cout<<"File reading stopped";
}

inFile.close();
return 0;

我需要代码在 .txt 文件中读取停止后立即停止读取 int。

我知道某些代码是完全错误的,但我已尝试搜索尽可能多的答案。

【问题讨论】:

  • 你的 C++ 教科书对这个主题有什么看法?
  • 如果你想阅读文本,你无法使用int
  • 您的意思是实际的字符串"stop" 还是stop 是一个特殊的数值?
  • 我在我的教科书中找不到任何东西
  • 是一个实际的停止字符串。

标签: c++ string loops int


【解决方案1】:
int sum = 0;

std::string aLine;

bool bFoundStop(false);

while (getline(inFile, aLine) && !bFoundStop)
{
    //the basic adding up of the numbers

    if(aLine == "stop")
    {
        bFoundStop = true;
    }
    else    
    {
        int x = atoi(aLine.c_str());
        sum += x;
    }

    std::cout<<sum<<std::endl;
}
inFile.close();

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 2018-06-22
    • 1970-01-01
    相关资源
    最近更新 更多