【问题标题】:How to read a string from a file with getline in c++?如何在 C++ 中使用 getline 从文件中读取字符串?
【发布时间】:2020-07-06 17:28:24
【问题描述】:

我有 2 个空白(保存和加载)。保存文件中的写入并从文件加载负载。问题是当我尝试从该文件中读取时,它只读取一个单词,即使使用 getline。

这是我的代码:

#include <iostream>
#include <windows.h>
#include <limits>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

float r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, puncte, rc1, rc2, rc3, rc4, rc5, rc6, rc7, rc8, rc9, rc10, var;
string q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;

void save()
{
ofstream outfile;
outfile.open("C:\\Users\\Public\\IntrebariTest.txt");
outfile << q1 << " " << q2 << " " << q3 << " " << q4 << q5 << " " << q6 << " " << q7 << " " << q8 << " " << q9 << " " << q10 << rc1 << " " << rc2 << " " << rc3 << " " << rc4 << rc5 << " " << rc6 << " " << rc7 << " " << rc8 << " " << rc9 << " " << rc10;
outfile.close();
}
void load()
{
ifstream infile;
infile.open("C:\\Users\\Public\\IntrebariTest.txt");
infile.getline(cin, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10);
infile >> rc1 >> rc2 >> rc3 >> rc4 >> rc5 >> rc6 >> rc7 >> rc8 >> rc9 >> rc10;
infile.close();
}

因此,如果有人知道导致问题的原因,请发表评论!谢谢! 错误是:

error: no matching function for call to 'std::basic_ifstream<char>::getline(std::istream&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&)'|

【问题讨论】:

  • 坦率地说,问题在于您猜测getline 的工作原理。没有需要 11 个参数的重载。您的代码将导致编译器错误,您应该将其包含在问题中
  • 我在帖子中添加了错误
  • 我认为您使用 getline 错误。此链接可能对您有所帮助:cplusplus.com/doc/tutorial/files
  • 你这样做完全错了,因为你应该根据文档来实现它。

标签: c++ codeblocks fstream


【解决方案1】:

没有

infile.getline(cin, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10);

但是

getline(infile, q1);
getline(infile, q2);
getline(infile, q3);
getline(infile, q4);
getline(infile, q5);
getline(infile, q6);
getline(infile, q7);
getline(infile, q8);
getline(infile, q9);
getline(infile, q10);

另外,如果你要读取行,那么你需要输出行。

没有

outfile << q1 << " " << q2 << " " << q3 << " " << q4 << q5 << " " << q6 << " " << q7 << " " << q8 << " " << q9 << " " << q10 << rc1 << " " << rc2 << " " << rc3 << " " << rc4 << rc5 << " " << rc6 << " " << rc7 << " " << rc8 << " " << rc9 << " " << rc10;

但是

outfile << q1 << "\n" << q2 << "\n" << q3 << "\n" << 
    q4 << "\n" << q5 << "\n" << q6 << "\n" << q7 << "\n" << 
    q8 << "\n" << q9 << "\n" << q10 << "\n" << 
    rc1 << " " << rc2 << " " << rc3 << " " << rc4 << " " << rc5 << " " << rc6 << " " << rc7 << " " << rc8 << " " << rc9 << " " << rc10;

当然,您的代码中如此多的重复应该提醒您有更好的方法来做到这一点。

【讨论】:

  • 非常感谢!你能解释一下另一种方法吗?
  • @D0WN70AD 使用字符串数组 q[],然后使用循环填充字符串 q[i]
  • 使用向量(或数组)和循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 2012-02-13
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多