簡體   English   中英

存儲字符串數組以及通過每個字符串進行解析的問題C ++

[英]Problems with storing array of strings, and parsing through each string C++

好的,基本上我的程序是從接受用戶輸入開始的。 輸入以整數n開頭,該整數指定要遵循的命令數。 在該行之后,將在每行上包含n行命令。 我試圖將每個命令作為字符串存儲在字符串數組中,然后嘗試處理每個字符串以找出命令的類型以及用戶在同一行上輸入的數字。

輸入示例:

。/一種

2

我1 2

我2 3

我希望我的程序然后將第一個input(2)下的每一行存儲到一個字符串數組中。 然后,我嘗試處理該行中的每個字母和數字。

我當前的代碼如下:

#include <iostream>
#include <string>
using namespace std;

int main() {
int number_of_insertions;
cin >> number_of_insertions;
cin.ignore();

string commandlist[number_of_insertions];

for(int i = 0; i < number_of_insertions; i++) {
    string command;
    getline(cin, command);
    commandlist[i] = command;
}


string command;
char operation;
int element;
int index;
for(int i = 0; i < number_of_insertions; i++) {
    command = commandlist[i].c_str();
    operation = command[0];

    switch(operation) {
        case 'I':
            element = (int) command[1];
            index = (int) command[2];
            cout << "Ran insertion. Element = " << element << ", and Index = " << index << endl;
            break;
        case 'D':
            index = command[1];
            cout << "Ran Delete. Index = " << index << endl;
            break;
        case 'S':
            cout << "Ran Print. No variables" << endl;
            break;
        case 'P':
            index = command[1];
            cout << "Ran print certain element. Index = " << index << endl;
            break;
        case 'J':
        default:
            cout << "Invalid command" << endl;

    }
 }  
}

然后,我對示例輸入的輸出如下:

然插入。 元素= 32,索引= 49

然插入。 元素= 32,索引= 50

完全不確定如何解決此問題,並期待獲得大家的幫助。

        element = (int) command[1];
        index = (int) command[2];

不要將command的第二和第三標記轉換為整數。 它們僅采用command的第二個和第三個字符的整數值,並將它們分別分配給elementindex

您需要做的是使用某種解析機制從command提取令牌。

std::istringstream str(command);
char c;
str >> c; // That would be 'I'.

str >> element;
str >> index;

等等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM