簡體   English   中英

用C ++中的文件輸入

[英]Input from a file in C++

我想逐個字符地讀取文件並對我使用以下循環的每個字符執行某個操作:

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

我不想在條件下讀取該字符,因為光標將移動到下一個位置,我將錯過該字符。 問題是文件末尾未正確發出信號,最后一個字符被讀取兩次。 請給出一種方法來避免這個例子。 如果文件中的字符串是軍隊,則將其視為軍隊(當我打印時)

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來讀取char ..在該示例中,您可以看到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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM