[英]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
的第二个和第三个字符的整数值,并将它们分别分配给element
和index
。
您需要做的是使用某种解析机制从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.