比较输入值和从文件中读取值的最佳方式

Best way to compare input values to read values from files

本文关键字:读取 最佳 方式 文件 输入 比较      更新时间:2023-10-16

我对c++编程还比较陌生,在这一切中我遇到了第一个主要障碍。。

我正试图弄清楚如何从记事本上的通用".txt"文件中读取值/字符。通过比较,我想确定是否读取整行,但我似乎不能只读取单个一位数或两位数,我让它使用{buffername.getline(variable,size)}读取整行,但当我试图将"size"更改为特定数字时,它会给我一个比较错误,说切换到"int"或"char"无效(取决于我如何声明变量)。

感谢您的帮助。感谢

  int length = 2;
  char * buffer;    
  ifstream is;
  is.open ("test.txt", ios::binary );    
  // allocate memory:
  buffer = new char [length];
  // read 2 char
  is.read (buffer,length);
  //Compare the character and decide     
  delete[] buffer;
  return 0;

您需要使用ifstream来获取值(ref 1)。

以下内容应该有效。在这里,我使用了一个std::string类型的单词,但您可以用其他类型(即:int、double等)来替换它

std::ifstream f("somefile.txt");   
std::string word;
std::string line;
if(f >> word){
    if(<the comparison>){
        line = f.getline();
    }
}

下面是如何使用ifstream 的扩展示例

首先,出于性能原因,一次读取1个字节是个坏主意。

我建议这个替代方案:

最好是整行阅读,然后使用字符数组。

char variable[1000];

将文件中的行读入变量。

if (variable[1]=='c') { printf("Byte 2 (remember 0 offset) is compared for the letter c";}

获得2位数的#

number=((variable[3]-48)*10)+(variable[4]-48);

您必须减去48,因为在ASCII中,数字0是48。