c++ - 如何从stringstream中跳过空格和换行符并将它们放入 vector 中?

标签 c++ string c++11 vector istringstream

我正在尝试读取一个文本文件,其中包含一个人的信息(姓名,年龄,职业),如下所示:

name 20
occupation
name 25
occupation
name 34
occupation
我阅读了整个文件,并为每一行使用istringstream跳过名称和年龄之间的空格。
std::vector<string> readfile(std::vector<std::string> *words, char *argv){

    std::ifstream file(argv);   //Opens the file specified on execution

    if ( !file ){
        cerr << "Le fichier " << argv << " n'existe pas" << endl;
        exit (-1);
    } else {
            std::string line;
            while (std::getline(file, line)){
                        istringstream ss(line);
                        do {
                                string word;
                                ss >> word;
                                if (word != " " || word != "\n"){
                                        words->push_back(word);
                                };
                        } while (ss);
                };
                file.close();
        };
        return *words;
};
我的主要是:
int main( int argc, char *argv[] ){
        std::vector<std::string> compV;

        readfile(&compV,argv[1]);
        cout << compV.at(2) << endl;
        
        return 0
}
当我编译并执行程序时,得到一个空格。compV.at(0)显示名称comV.at(1)显示年龄
但是comV.at(2)显示的是空格而不是占领。
我在这里做错了什么?

最佳答案

你可以做

string mystr;
    
while(file >> myStr) {
  string name = mystr;
  file >> mystr;
  int age = stoi(mystr);
  file >> mystr;
  int occupation = stoi(mystr);
}
只要您知道从文件中获取信息的顺序
您可以遵循上面的想法。
当您执行file >> mystr时,它将获得下一个单词/数字,直到空格,
一旦获得名称,这种情况下的下一个信息就是该行末尾的age,因此它将向下移动并再次执行相同的过程直到文件结束。
使用getline,您将获得整条线。
这是一个示例程序。
这是.txt文件
ADD A 1 2 3 4 5 6 7 8 9 10 11 12 STOP
ADD B 4 6 8 10 12 14 16 STOP
和程序
   SetT<int> a;
   SetT<int> b;
   string mystr, str;
   ifstream testFile;
   testFile.open("testDrive.txt");
        
   if(testFile){
       while(testFile >> mystr){
           if(mystr == "ADD"){
               testFile >> mystr;
               if(mystr == "A"){
                    while(testFile >> mystr && mystr != "STOP"){
                        stringstream(mystr) >> num;
                        cout << "A : ";
                        a.Add(num);
                    }
                } else {
                    while(testFile >> mystr && mystr != "STOP"){
                        stringstream(mystr) >> num;
                        cout << "B : ";
                        b.Add(num);
                    }
                }
                    
           }
        }
    }

关于c++ - 如何从stringstream中跳过空格和换行符并将它们放入 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62508522/

相关文章:

C++ 将函数的输出发送到 cout

c++ - 使用 Ruby on Rails 进行复杂算法

c++ - 为什么 std::array::size 不是静态的?

string - 什么是字典顺序?

c++ - 如何在递归函数中将字符串捕获到变量中?

c++ - 没有辅助变量的 std::vector 中的 Pushing_back 值

c++ - 创建抽象包装迭代器

C++: std::string 问题

c++ - std::queue 位置的包装器

c++ - 重构嵌套绑定(bind)以使用 lambda 函数