【问题标题】:Read text file into string. C++ ifstream [duplicate]将文本文件读入字符串。 C ++ ifstream [重复]
【发布时间】:2012-11-13 03:59:14
【问题描述】:
void docDB(){
     int sdb = 0;
     ifstream dacb("kitudacbiet.txt");
     if(!dacb.is_open())
         cout<<"Deo doc dc file"<<endl;
     else{
          while(!dacb.eof()){
               dacb>>dbiet[sdb].kitu;
               dacb>>dbiet[sdb].mota;
               //getline(dacb,dbiet[sdb].mota);
               /*
               string a="";
               while((dacb>>a)!= '\n'){
                //strcat(dbiet[sdb].mota,a);
                dbiet[sdb].mota+=a;
               }
               */
               sdb++;
          }
     }

}

文本文件:“kitudacbiet.txt”

\ Dau xuyet phai
@ Dau @
# Dau #
$ Ky hieu $
( Dau mo ngoac
) Dau dong ngoac

我想将第一行字符串读入 dbiet[sdb].kitu 并将其余行读入 dbiet[sdb].mota

示例:第 1 行 = \ Dau xuyet phai

dbiet[sdb].kitu = "\" 和 dbiet[sdb].mota = "Dau xuyet phai"

我想逐行阅读,直到遇到下线字符('\n')。这个怎么做。 对不起,我的英语不好。谢谢

【问题讨论】:

  • 您要求while (!eof()) 的错误。
  • 我不知道你在问什么!
  • 没有。我想将第一行字符串读入 dbiet[sdb].kitu 并将其余行读入 dbiet[sdb].mota 示例:line \ Dau xuyet phai dbiet[sdb].kitu = "\" and dbiet[sdb].mota = "Dau xuyet phai" 感谢您的帮助。
  • eof() 总是错的。

标签: c++ ifstream


【解决方案1】:

看起来您正在尝试解析每一行。另一个答案向您展示了如何在循环中使用getline 来分隔每一行。您需要的另一个工具是 istringstream,用于分隔每个令牌。

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

【讨论】:

  • 我尝试使用您的代码,但应用程序只能读取最后一行
  • ostringstream*
【解决方案2】:

getline(fin, buffer, '\n')
fin 是打开的文件(ifstream 对象),bufferstring/char 类型的您要复制行的位置。

【讨论】:

    【解决方案3】:

    要将文件中的整行读入字符串,请使用std::getline,如下所示:

     std::ifstream file("my_file");
     std::string temp;
     std::getline(file, temp);
    

    您可以循环执行此操作,直到文件结束,如下所示:

     std::ifstream file("my_file");
     std::string temp;
     while(std::getline(file, temp)) {
          //Do with temp
     }
    

    参考文献

    http://en.cppreference.com/w/cpp/string/basic_string/getline

    http://en.cppreference.com/w/cpp/string/basic_string

    【讨论】:

    • 我尝试使用您的代码,但应用程序只读取了最后一行
    • @HoangQBH 你能显示你想要的输入,想要的输出(不是不正确的输出)和你用std::getline尝试过的代码
    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2015-07-30
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多