【问题标题】:Problems with storing array of strings, and parsing through each string C++存储字符串数组和解析每个字符串 C++ 的问题
【发布时间】:2015-09-20 03:30:06
【问题描述】:

好的,基本上我的程序从接受用户输入开始。输入以整数 n 开头,指定要遵循的命令数。在该行之后将有 n 行,每行都有一个命令。我试图将这些命令中的每一个作为字符串存储在字符串数组中,然后我试图处理每个字符串以找出它是什么类型的命令以及用户在同一行输入的数字。

示例输入:

./a

2

我 1 2

我 2 3

我希望我的程序将第一个输入 (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

完全不知道如何解决这个问题,期待得到大家的帮助。

【问题讨论】:

    标签: c++ arrays string


    【解决方案1】:

    线条

            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;
    

    等等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多