使用file.get()与整数值

huangapple go评论98阅读模式
英文:

Using file.get() with integer values

问题

我需要使用get()函数来读取数值。我有以下处理输入字符的代码的一部分。如何更新这段代码,以正确使用get()函数来读取数值?

  1. in_file.open(in_file_name, ios::in);
  2. in_file.get(id); // 我需要使用这个id,它是int类型。在原始代码中,它是char类型。
  3. while (!in_file.eof())
  4. {
  5. in_file.get(id);
  6. }
  7. in_file.close();

我遇到的错误是:

错误:无法将类型为非const左值引用绑定到类型为std::basic_istream<char>::char_type&的rvalue上,std::basic_istream<char>::char_typechar

如何修复这个错误?

英文:

I need to read numeric values by using get().
I have this code that deal with char as input this is a part of the code. How can update on this code to use get() with values in correct way?

  1. in_file.open(in_file_name, ios::in);
  2. in_file.get(id); // id that I need to use it,int id. With original code
  3. // was char id;
  4. while (!in_file.eof())
  5. {
  6. in_file.get(id);
  7. }
  8. in_file.close();

The error that I have:

> error: cannot bind non-const lvalue reference of type
> 'std::basic_istream<char>::char_type&' {aka 'char&'} to an rvalue of
> type 'std::basic_istream<char>::char_type' {aka 'char'}
> in_file.get(id);

答案1

得分: 1

使用&gt;&gt;而不是get来读取整数。此外,您的while循环是错误的。以下是正确的代码:

  1. in_file.open(in_file_name, ios::in);
  2. while (in_file >> id)
  3. {
  4. ...
  5. }
  6. in_file.close();
英文:

To read integers use &gt;&gt; not get. Plus your while loop is wrong. Here's the correct code

  1. in_file.open(in_file_name, ios::in);
  2. while (in_file &gt;&gt; id)
  3. {
  4. ...
  5. }
  6. in_file.close();

huangapple
  • 本文由 发表于 2023年7月31日 19:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定