取多行输入,以逗号分割,将每一行存储到字符串数组中

时间:2016-10-09 20:40:30

标签: c++ arrays string

以下是我将要使用的输入类型的示例: (来自标准输入)

Archery,M,TEAM,Archery,Lord's Cricket Ground,1. GOLD,team ITA,Italy
Archery,M,TEAM,Archery,Lord's Cricket Ground,2. SILVER,team USA,United States
Archery,M,TEAM,Archery,Lord's Cricket Ground,3. BRONZE,team KOR,South Korea
Cycling,M,IND,Road,Regent's Park,1. GOLD,Aleksander Winokurow,Kazakhstan
Cycling,M,IND,Road,Regent's Park,2. SILVER,Rigoberto Uran,Colombia
Cycling,M,IND,Road,Regent's Park,3. BRONZE,Alexander Kristoff,Norway
Fencing,F,IND,Foil,ExCeL,1. GOLD,Elisa Di Francisca,Italy
InsertionEnd

正如标题所暗示我想要获取每一行,将其拆分为逗号,并将这些字符串中的每一个存储到一个数组(或字符串向量)中。然后我想获取数组中的每个项目并将其用作函数的参数。我知道如何读取多行以及如何分割字符串,但是当我把这些东西放在一起时,它并不适合我。

我的思路:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;
int main()
{
    string line;
    stringstream ss(line);

while (line != "InsertionEnd") {

    vector<string> array;
    getline(ss, line, ',');
    array.push_back(line);
    addItem(array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7])
    }
}

所以在我得到我的数组后,我想使用我创建的addItem函数,它只创建一个运动员结构(需要8个参数)。像这样:

myTable.addItem("Archery","M","TEAM","Archery","Lord's Cricket Ground","1. GOLD","team ITA","Italy");

我是否在正确的轨道上?还是这完全不合适?感谢。

注意:我已经测试了addItem函数,只需自己输入参数就可以了。

2 个答案:

答案 0 :(得分:3)

你的想法是正确的;但你在代码中犯了一些错误:
  - array.push_back(line); - 您正在初始化空字符串上的字符串流;您需要先输入该行,然后将其插入到stringstream中   - line - 您正在将字符串#include <iostream> #include <vector> #include <string> #include <sstream> using namespace std; int main() { string line; vector<vector<string>> array; while ( true ) { getline ( cin, line ); if ( line == "InsertionEnd" ) { break; } stringstream ss ( line ); string word; vector<string> vector_line; while ( getline ( ss, word, ',' ) ) { vector_line.push_back ( word ); } array.push_back ( vector_line ); } } 直接推送到结果向量;你需要先把它分解成组成单词。

以下代码为您的问题实现了一个可行的解决方案:

create_table "working_hours", force: :cascade do |t|
  t.integer  "day"
  t.time     "open_time"
  t.time     "close_time"
  t.integer  "venue_id"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
  t.index ["merchant_id"], name: "index_working_hours_on_merchant_id", using: :btree
end

答案 1 :(得分:2)

这是一个正确循环输入的解决方案,分割每一行并使用提取的标记调用addItem

string line;
while (getline(cin, line)) { // for each line...
    if (line == "InsertionEnd") break;

    // split line into a vector
    vector<string> array;
    stringstream ss(line);
    string token;
    while (getline(ss, token, ',')) { // for each token...
        array.push_back(token);
    }

    // use the vector
    addItem(array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);
}