【问题标题】:ifstream does not return the correct int valueifstream 不返回正确的 int 值
【发布时间】:2015-09-23 11:48:51
【问题描述】:

我想创建一个工厂类,从文件中创建和加载对象; 但是,当我尝试从文件中读取 int 时,它似乎返回了错误的数字。

std::ifstream input;
input.open("input.txt");
if (!input.is_open()){
    exit(-1);

}

int number;

input >> number;
cout << number;

input.close();

当我在input.txt 文件中输入一个数字时,它会显示:-858993460。 更改数字并没有什么不同,当我使用 cin 而不是 ifstream 时,它的工作原理应该是这样。我可能只是错过了一些非常愚蠢的东西,但我无法弄清楚。

编辑:使用getLine() 可以正常工作。我猜使用>>有问题。

【问题讨论】:

标签: c++ file-io ifstream


【解决方案1】:

这是另一种打开文件并逐行读取的解决方案:

string line;
ifstream myfile("input.txt");
if (myfile.is_open())
{
  while ( getline (myfile,line) )
  {
    cout << line << '\n'; // Use this to verify that the number is outputed
    // Here you can transform your line into an int:
    // number = std::stoi(line);
  }
  // myfile.close(); Use this if you want to handle the errors
}

else cout << "Unable to open file";

如果您不想逐行阅读,只需删除while

...
getline(myfile,line);
number = std::stoi(line);
...

在一行中读取多个数字

你的输入文件是这样的:

1、2.3、123、11

1, 2

0.9, 90

然后,你可以使用这段代码来读取所有的数字:

string line;
ifstream myfile("input.txt");
string delimiter = ", ";

if (myfile.is_open())
{
  while ( getline (myfile,line) )
  {
    cout << "Reading a new line: " << endl;
    size_t pos = 0;
    string token;
    while ((pos = line.find(delimiter)) != string::npos) {
      token = line.substr(0, pos);
      cout << token << endl; // Instead of cout, you can transform it into an int
      line.erase(0, pos + delimiter.length());
    }
  }
}
else cout << "Unable to open file";

输出将是:

Reading a new line: 
1
2.3
123
11
Reading a new line:
1
2
Reading a new line:
0.9
90

可能有效的新解决方案 =)

我没有对此进行测试,但它显然有效:

std::ifstream input;
double val1, val2, val3;
input.open ("input.txt", std::ifstream::in);
if (input >> val1 >> val2 >> val3) {
  cout << val1 << ", " << val2 << ", " << val3 << endl;
}
else
{
  std::cerr << "Failed to read values from the file!\n";
  throw std::runtime_error("Invalid input file");
}

要检查 IO,请参阅http://kayari.org/cxx/yunocheckio.html

【讨论】:

  • myfile.close() 有什么意义?你不相信析构函数吗?
  • 我有总是关闭流的习惯,即使它们有析构函数..我不知道这是一个好习惯还是坏习惯.. =) 但它通常不会改变任何东西..
  • 重点是我想读取和分配多个值,所以我可以使用: input >> x >> y >> health;或类似的东西
  • @Jasper:我可能发现了一些更容易使用的东西。显然,您在打开文件时错过了std::infstream::in..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 2021-10-26
  • 2015-10-13
相关资源
最近更新 更多