存储字符串数组和解析每个字符串的问题
Problems with storing array of strings, and parsing through each string C++
好的,基本上我的程序从一个用户输入开始。输入以整数n开头,指定要跟随的命令的数量。该行之后将有n行,每行上有一个命令。我试图将这些命令中的每一个作为字符串存储在字符串数组中,然后我试图处理每个字符串以找出它是什么类型的命令以及用户在同一行输入的数字。
示例输入:
/
2I 1 2
I 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;
}
}
}
然后我的输出示例输入如下:
插入。Element = 32, and Index = 49
插入。Element = 32, and Index = 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;
等。
相关文章:
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题