从C++中的文件输入

Input from a file in C++

本文关键字:文件 输入 C++      更新时间:2023-10-16

我想逐个字符地从文件中读取,并使用以下循环对每个字符执行特定操作:

 ifstream in
 while(in)
 {
    ch=in.get();
    //some operation
  }

我不想在一段时间内阅读条件下的字符,因为那个时光标会移动到下一个位置,我会错过那个字符。问题是文件的末尾没有正确地发出信号,最后一个字符被读取了两次。请给出避免这种情况的方法如果文件中的字符串是军队它被读取为armyy(当我打印时)

char ch;
while(in.get(ch)){ }  //or in>>std::noskipws>>c

将是您想要的字符存储在ch中的正确方式。那有什么问题?

如果你真的想要你想要的方式,那么你可以使用peek()来查看下一个字符,并执行适当的操作:

char c = in.peek(); //this will give you the next character in the stream
//if its an eof, do appropriate

使用get:的其他重载

while (in.get(ch)) {
  // do something with ch
}

for (char ch; in.get(ch); ) {
  // do something with ch
}

您也可以使用sscanf读取字符。。在该示例中,您可以看到3个输入是从文本中读取的。前两个是字符串,最后一个是浮点。。还可以使用向量来存储值。。希望这个例子能对有所帮助

  std::string str;
   char buf_1[50];
   char buf_2[50];
   while(std::getline(in, str))
   {
       if(sscanf(str.c_str(), "%s %s %f", buf_1, buf_2, &faceStatistics.statistics) == 3)
       {
           faceStatistics.faceName_1 = buf_1;
           faceStatistics.faceName_2 = buf_2;
           faceStat_.push_back(faceStatistics);
       }
        else
            std::cout << "No param in string  " << str << std::endl;
   }

矢量分配

struct Fstat {
   std::string faceName_1;
   std::string faceName_2;
   float statistics;
};