[英]C++ std::getline result string won't let me concatenate another string to it
我正在嘗試從.txt文件中讀取數據,該文件只包含名稱列表。 我要為每個名稱執行以下操作:
1) read a name and store it in a string variable.
2) Add quotes to the name ("name")
3) make a map entry using each name (map["name"]= x)
我正在使用std :: getline函數讀取每一行,並且嘗試通過使用(string name =“ \\”“ + line +” \\“”)簡單地添加引號。 問題在於,每次我在行字符串的末尾添加任何內容時,都不會添加任何內容!
這是我的代碼:
#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main(){
ifstream reader("input.txt");
string line;
string name;
map<string,int> arr;
int np=5;
for(int i=0;i<np;i++){
getline(reader,line);
name="\"" +line +"\"";
cout<< name << endl;
}
return 0;
}
這是我的輸入txt文件:
dave
laura
owen
vick
amr
這是我當前得到的輸出:
"dave
"laura
"owen
"vick
"amr"
非常感謝你!
我想您的輸入行以\\ r \\ n結尾,而您的getline
讀取直到'\\ n'。 如果是這樣,那么解決方案是在行尾手動刪除\\ r char:
getline(reader,line);
line.pop_back();
[編輯]
或代替pop_back()
:
auto cr_pos = line.rfind('\r');
if ( cr_pos != std::string::npos )
line = line.substr(0, cr_pos);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.