题目描述
在命令行输入如下命令:
xcopy /s c:\ d:\,
各个参数如下:
参数1:命令字xcopy
参数2:字符串/s
参数3:字符串c:\
参数4: 字符串d:\
请编写一个参数解析程序,实现将命令行各个参数解析出来。
解析规则:
1.参数分隔符为空格
2.对于用“”包含起来的参数,如果中间有空格,不能解析为多个参数。比如在命令行输入xcopy /s “C:\program files” “d:\”时,参数仍然是4个,第3个参数应该是字符串C:\program files,而不是C:\program,注意输出参数时,需要将“”去掉,引号不存在嵌套情况。
3.参数不定长
4.输入由用例保证,不会出现不符合要求的输入
示例1
输入
xcopy /s c:\ d:\
输出
4
xcopy
/s
c:\
d:\
#include <iostream>
#include <string>
using namespace std;
//参数解析
int main1()
{
string s1;
while (getline(cin, s1))
{
int sum = 0;
for (int i = 0; i < s1.size(); i++)
{
if (s1[i] == ' ')
{
sum++;
}
//判断有没有双引号,双引号中的空格是需要打印出来的
if (s1[i] == '"')
{
do
{
i++;
} while (s1[i] != '"');
}
}
cout << sum + 1<< endl;
int flag = 1;
for (int i = 0; i < s1.size(); i++)
{
//有双引号,下一次遇见双引号,flag异或
if (s1[i] == '"')
{
flag ^= 1;
}
//双引号和普通空格不需要打印
if (s1[i] != ' ' && s1[i] != '"')
{
cout << s1[i];
}
//双引号中的空格打印
if (s1[i] == ' ' && (!flag))
{
cout << s1[i];
}
//遇到双引号之外的空格换行
if (s1[i] == ' ' && flag)
{
cout<<endl;
}
}
cout << endl;
}
system("pause");
return 0;
}