【发布时间】:2021-12-27 04:48:53
【问题描述】:
我是 C++ 新手,在阻止 getline 读取文本文件末尾的换行符时遇到了一些问题。我尝试使用换行符截断它,然后用','传递给定界符,但它不起作用。您能否帮助我了解发生了什么以及为什么我无法实现我想要做的事情?
我已经编辑了这篇文章以更正 getline() 的错误,而不是可用的。但是我不知道如何传输这个 getline() 字符串以防止使用'\n' 字符
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
static int Ncol = 5;
int main()
{
int ctr=0,Nrow;
std::string line,line1;
std::ifstream myFile1;
Nrow = 4;
std::cout.precision(15);
std::fixed;
double* input = new double[Nrow*Ncol];
double* ftrue = new double[Nrow];
myFile1.open("./Data_codelink_test/test.txt");
while(ctr<Nrow)
{
std::getline(myFile1,line1,','); // This gives me line1 with the new line character
std::cout<<"Read "<<line1<<std::endl;
input[ctr] = std::stold(line1);
std::cout<<"Stored "<<input[ctr]<<std::endl;
ctr++;
}
myFile1.close();
我的 test.txt 是这样的
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
我想要一个大小为 20 的向量以这种方式存储值
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
【问题讨论】:
-
当
getline失败时,它返回false。这段代码并没有对此进行检查,因此它会继续其愉快的方式。 -
@RemyLebeau 感谢您指出这一点。但即使我在 while 循环中将 getline() 限制为适当的数量,它也不能解决我的主要问题。我看不出如何防止 std::getline(myFile1,line,',') 在每行末尾获取 '\n' 值。对此的任何建议将不胜感激。谢谢
-
@readysetcode "它不能解决我的主要问题" - 究竟是什么?你没有解释清楚。 “我看不到如何防止 std::getline(myFile1,line,',') 在每行末尾获取 '\n' 值” - 这正是确实如此。它仅在读取 specified 分隔符时停止。如果它对您不起作用,那么还有其他问题。 “它不起作用”不是一个有用的描述。为什么你认为它不起作用?请详细说明。
-
@readysetcode 现在您已将代码更改为使用 1
getline()而不是 2。这从根本上改变了代码的行为(并使我的答案无效)。以前的代码实际上在解决您的问题方面做得更好,这个新代码引入了您所询问的问题。请还原代码,然后解释为什么原始代码不适合您。
标签: c++ getline comma stringstream removing-whitespace