预先对不起,因为我是编程新手,代码中的某些内容可能看起来完全是胡说八道!我不确定自己是否使用atoi
正确。
我正在尝试创建一个程序,将用户输入的句子拆分为单个单词,如果用户输入一个,则将数字(浮点数/整数)加倍。例如,I have 3 cats
结果如下:
I
have
6
cats
我的程序现在可以拆分句子,但是我无法使整数翻倍。谁能帮我这个?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char sentence[100];
printf("Enter a sentence to split: ");
scanf("%[^\n]s", sentence);
char *pch;
int y;
y = atoi(sentence);
printf("After splitting:\n", sentence);
pch = strtok(sentence," ");
while (pch != NULL) {
printf("%s\n", pch);
pch = strtok(NULL, " ");
}
system("PAUSE");
}
到目前为止,我的输出是:
Enter a sentence to split: Hi, I have 7 cats.
After splitting:
Hi,
I
have
7
cats.
Press any key to continue . . .
这是一个测试所有数字的简单版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char sentence[100];
char *pch;
printf("Enter a sentence to split: ");
if (!fgets(sentence, sizeof sentence, stdin))
return 1;
printf("After splitting:\n");
for (pch = strtok(sentence, " \n"); pch != NULL; pch = strtok(NULL, " \n")) {
if (pch[strspn(pch, "0123456789")] == '\0') {
printf("%d\n", atoi(pch) * 2);
} else {
printf("%s\n", pch);
}
}
system("PAUSE");
return 0;
}
如果您也想解析浮点数,则可以使用以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void) {
char sentence[100];
char *pch, *pend;
double value;
printf("Enter a sentence to split: ");
if (!fgets(sentence, sizeof sentence, stdin))
return 1;
printf("After splitting:\n");
for (pch = strtok(sentence, " \n"); pch != NULL; pch = strtok(NULL, " \n")) {
value = strtod(pch, &pend);
if (*pend == '\0' && isfinite(value)) {
printf("%g\n", value * 2);
} else {
printf("%s\n", pch);
}
}
system("PAUSE");
return 0;
}
注意测试isfinite()
是为避免inf
和nan
数字。
注意:isfinite
它是C99的一部分,VisualStudio 12不支持它,但较新的版本支持它。对于此旧版本,请使用中_finite()
定义<float.h>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句