【问题标题】:read string with whitespaces from file从文件中读取带有空格的字符串
【发布时间】:2014-04-13 11:01:47
【问题描述】:

所以基本上,我正在制作一个简单的程序,它从文件 s 中获取名称,然后询问是否应该将它们写入另一个文件。

void ziureti(){
      string pavadinimas, statymas, laimejo;
      double kofas; //these are irrelevant to the problem
      int suma; //these are irrelevant to the problem
      cout << "Enter the name: ";
      getline(cin, statymas);
      ifstream fd (FV);
      while (statymas != pavadinimas ){ //out here I iterate through the file until i find the neccesary name
      fd >> pavadinimas;}

因此,当名称只有数字或字母时,它很好,但是当两者都存在时,程序找不到它们。有什么想法吗?

例如

Chelsea
10
1.8
Arsenal
15
2.3
Chelsea Arsenal
15
1.85

Chelsea Arsenal 应该是一个字符串,我该怎么做?

【问题讨论】:

  • 你能举一个输入文件失败的例子吗?
  • 好吧对不起,我弄乱了文件名和保存,但是当字符串中有空格时它仍然不起作用。我将如何解决这个问题? ` 切尔西 10 1.8 阿森纳 15 2.3 切尔西阿森纳(这应该是一串) 15 1.85 ` @celtschk
  • operator&gt;&gt; 在空格处拆分。您可能还想在fd 上使用getline
  • @Marsietis 请编辑您的问题以添加更多信息。在 cmets 中它非常没用。

标签: c++ string text file-io


【解决方案1】:

改变

fd >> pavadinimas;        // ">>" will stop parsing when hitting spaces

getline(fd, pavadinimas); // will parse the whole line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多