我试图从.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函数来读取每一行,并且我试图仅使用(字符串名称=" \"" + 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"
非常感谢!
答案 0 :(得分:1)
我想你的输入行以\ r \ n结尾,而你的getline
读到'\ n'。如果这是真的那么解决方案是在行尾删除手动\ rc 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);