[英]cout not printing string of vector after getline
我有一個 .csv 文件,其內容如下:
1.0,2.0
2.0,3.0
現在我想讀取這個文件並將其打印到終端。 我希望 output 看起來像這樣:
1.0|2.0|
2.0|3.0|
但我得到的是:
|
|
當我運行調試器時,向量包含正確的數據,但它不會打印它。
cout(調試器)時的向量數組:
array = {std::vector<std::vector>}
[0] = {std::vector<std::basic_string, std::allocator>}
[0] = {std::basic_string<char, std::char_traits, std::allocator>} "1.0"
[1] = {std::basic_string<char, std::char_traits, std::allocator>} "2.0\r"
[1] = {std::vector<std::basic_string, std::allocator>}
[0] = {std::basic_string<char, std::char_traits, std::allocator>} "2.0"
[1] = {std::basic_string<char, std::char_traits, std::allocator>} "3.0\r"
我的代碼:
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <fstream>
int main()
{
using namespace std;
ifstream in("C:\\Users\\freit\\CLionProjects\\Aufgabe2\\data.csv", ios_base::in);
string line, field;
vector< vector<string> > array; // the 2D array
vector<string> v; // array of values for one line only
while ( getline(in,line) ) // get next line in file
{
v.clear();
stringstream ss(line);
while (getline(ss,field,',')) // break line into comma delimited fields
{
v.push_back(field); // add each field to the 1D array
}
array.push_back(v); // add the 1D array to the 2D array
}
// print out what was read in
for (size_t i=0; i<array.size(); ++i)
{
for (size_t j=0; j<array[i].size(); ++j)
{
cout.flush();
cout << array[i][j] << "|"; // (separate fields by |)
}
cout << "\n";
}
return 0;
}
問題出在我想閱讀的data.cls
中。 調試器在每一行的末尾顯示一個\r
(轉義序列)。 這可能是在使用 Excel 打開data.cls
並勾選自動保存后出現的。 使用標准 windows 文本編輯器編寫新的data.cls
后,問題得到解決。 感謝評論,得到了解決方案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.