从命令行,我想编写一个for循环,它将从命令行参数中检测数组中是否有字符串或char。
例如,某人输入4.3, 5, 99, 0.1, w, 4, 2.43
。当循环检测到char w时,它将打印“Error”。如果输入为4.3, 5, 99, 0.1, wasabi, 4, 2.43
,则同样如此;当循环检测到字符串wasabi
时,它将显示错误消息。我无法弄清楚的是如何编写循环以便它检测任何字符或字符串,无论它在数组中的哪个位置。这就是我到目前为止所做的:
//check for a string or char in array
void checkForWord(int argc, char* argv[])
{
for (int i = 1; i < argc - 1; i++)
{
if ()
{
//do something..
}
}
}
任何帮助都将非常感谢!!
答案 0 :(得分:0)
可能是这样的:
for (int i = 1; i < argc; i++) // Don't do argc - 1 when using <
{
string s = argv[i];
for (auto c : s)
{
if (c != ',' && c != '.' && !isdigit(c))
{
cout << "Error" << endl;
return;
}
}
}
注意:这会接受4....3,,,,, 5, 99, 0.1, 4, 2.43
之类的输入,因为代码不会检查.
的数量和,
的数量
答案 1 :(得分:0)
你走了。完整的工作示例:
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
int main(int argc, const char* const* argv)
{
// first, concatenate the command line arguments into a continuous buffer
std::string buffer;
auto sep = "";
for(int i = 1 ; i < argc ; ++i)
{
buffer += sep;
buffer += argv[i];
sep = " ";
}
// now turn the buffer into a string stream
auto stream = std::istringstream(buffer);
// now stream in my numbers, delimited by commas
std::string val_buffer;
while (std::getline(stream, val_buffer, ','))
{
// make a new string stream, just to parse the text into a number
auto num_stream = std::istringstream(val_buffer);
double val = 0;
if (num_stream >> val)
{
// parsed correctly. now let's do something with it
std::cout << "found a value: " << val << std::endl;
}
else
{
// whatever that was, it wasn't a number
std::cout << "found a something I didn't like: " << val_buffer << std::endl;
break;
}
}
if (stream.bad())
{
std::cout << "something bad happened" << std::endl;
}
return 0;
}
使用命令行4.3, 5, 99, 0.1, wasabi, 4, 2.43
执行时结果:
found a value: 4.3
found a value: 5
found a value: 99
found a value: 0.1
found a something I didn't like: wasabi
没有芥末的结果:
found a value: 4.3
found a value: 5
found a value: 99
found a value: 0.1
found a value: 4
found a value: 2.43