[英]Testing for int in a string vector
I'm writing a program where I need to get a line of input that consists of a letter and two numbers with spaces in between.Let's say,something like "I 5 6". 我正在编写一个程序,我需要获得一行输入,其中包含一个字母和两个数字,其间有空格。让我们说,像“I 5 6”。
I use std::getline to get input as a string so there wouldn't be any problems with the blank space and then a for loop to browse through the individual characters in the string. 我使用std :: getline来获取字符串输入,这样就不会有任何空白问题,然后用for循环来浏览字符串中的各个字符。 I need a certain condition to execute only if the 2nd and 3rd characters(3rd and 5th counting the blanks) are numbers.
只有当第2个和第3个字符(计算空白的第3个和第5个字符)是数字时,我才需要执行某个条件。
How can I test if a character at a certain position in a string is an int? 如何测试字符串中某个位置的字符是否为int?
For your purpose, I would put the line into an std::istringstream
and use the normal stream extraction operator to get the values from it. 为了您的目的,我将该行放入
std::istringstream
并使用普通流提取运算符从中获取值。
Perhaps something like 也许是这样的
char c;
int i1, i2;
std::istringstream oss(line); // line is the std::string you read into with std::getline
if (oss >> c >> i1 >> i2)
{
// All read perfectly fine
}
else
{
// There was an error parsing the input
}
You can use isalpha
. 你可以使用
isalpha
。 Here is an example: 这是一个例子:
/* isalpha example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i=0;
char str[]="C++";
while (str[i])
{
if (isalpha(str[i])) printf ("character %c is alphabetic\n",str[i]);
else printf ("character %c is not alphabetic\n",str[i]);
i++;
}
return 0;
}
isalpha
Checks whether c is an alphabetic letter. isalpha
检查c是否是字母。 http://www.cplusplus.com/reference/cctype/isalpha/ http://www.cplusplus.com/reference/cctype/isalpha/
The output will be: 输出将是:
character C is alphabetic character + is not alphabetic character + is not alphabetic
字符C是字母字符+不是字母字符+不是字母
And for digits use isdigit
: 对于数字使用
isdigit
:
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char str[]="1776ad";
int year;
if (isdigit(str[0]))
{
year = atoi (str);
printf ("The year that followed %d was %d.\n",year,year+1);
}
return 0;
}
The output will be: 输出将是:
The year that followed 1776 was 1777
1776年之后的那一年是1777年
isdigit
Checks whether c is a decimal digit character. isdigit
检查c是否为十进制数字字符。 http://www.cplusplus.com/reference/cctype/isdigit/ http://www.cplusplus.com/reference/cctype/isdigit/
There is a function isdigit()
for it: 它有一个函数
isdigit()
:
To check 2nd and 3rd characters of a string s
you can use this code: 要检查字符串的
s
2个和第3个字符,可以使用以下代码:
if (isdigit(s[2]) && isdigit(s[3]))
{
// both characters are digits
}
But in your case ( s == "I 5 6"
) it seems that you need to check s[2]
and s[4]
. 但在你的情况下(
s == "I 5 6"
)你似乎需要检查s[2]
和s[4]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.