简体   繁体   English

用C ++中的文件输入

[英]Input from a file in C++

I want to read from a file character by character and perform a certain operation on every character I am using the following loop: 我想逐个字符地读取文件并对我使用以下循环的每个字符执行某个操作:

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

I don't want to read the character in condition for while because then cursor will move to next position and I'll miss that character. 我不想在条件下读取该字符,因为光标将移动到下一个位置,我将错过该字符。 The problem is that the end of the file is not properly signalled and the last character is read two times. 问题是文件末尾未正确发出信号,最后一个字符被读取两次。 Please give a way to avoid this Eg. 请给出一种方法来避免这个例子。 if The string in the file is army it is read as armyy (when I print) 如果文件中的字符串是军队,则将其视为军队(当我打印时)

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

Would be the proper way as the character you want is stored in ch . 因为你想要的角色存储在ch ,这将是正确的方式。 what is the problem with that? 有什么问题?

If you really want it the way you want, then you may use peek() to see the next character and perform appropriate opeartion as: 如果你真的想要它,你可以使用peek()来查看下一个字符并执行适当的操作:

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

Use the other overload of get: 使用get的另一个重载:

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

or 要么

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

You can also use sscanf for reading char.. In that example you can see that 3 input are reading from text . 您还可以使用sscanf来读取char ..在该示例中,您可以看到3个输入正在从文本中读取。 First two are string , last is float .. And also you can use a vector to store values.. Hope this example can be helpfull 前两个是字符串,最后是浮点数。还可以使用向量来存储值。希望这个例子可以有用

  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;
   }

vector assign 矢量分配

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM