【问题标题】:How to skip the space and the new line from stringstream and put them in a vector?如何跳过字符串流中的空格和新行并将它们放入向量中?
【发布时间】:2020-10-11 23:11:10
【问题描述】:

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

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) 显示的是空格而不是占用。

我在这里做错了什么?

【问题讨论】:

  • 为什么要打开文件两次? word != " " || word != "\n" 永远不会是 false
  • 哦,我实际上并没有纠正那个,我的错

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


【解决方案1】:

你可以的

string mystr;
    
while(file >> myStr) {
  string name = mystr;
  file >> mystr;
  int age = stoi(mystr);
  file >> mystr;
  int occupation = stoi(mystr);
}

只要您知道从文件中获取信息的顺序 你可以按照上面的思路。

当您执行file &gt;&gt; mystr 时,它将获取下一个单词/数字,直到空白, 获得名称后,在这种情况下,下一个信息将是年龄,在行尾之后,因此它将向下移动并再次执行相同的过程,直到文件结束。

使用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);
                    }
                }
                    
           }
        }
    }

【讨论】:

  • 成功了,感谢getlinefile &gt;&gt; mystr之间的解释
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多