我一直在尝试编写一个程序,该程序将读取一系列空格分隔的整数,直到遇到换行符。我的方法是将输入作为字符串读取,并使用 atoi()
来将字符串转换为整数。
这是我的方法:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
int a[100],i=0,k=0;
char s[100];
//Read the first character
scanf("%c",&s[i]);
//Reads characters until new line character is encountered
while(s[i]!='\n'){
i+=1;
scanf("%c",&s[i]);
}
//Print the String
printf("\nstring = %s\n",s);
//Trying to convert the characters in the string to integer
for(i=0;s[i]!='\0';i++){
if(isdigit(s[i]))
{
a[k] = atoi(s);
k+=1;
}
}
//Printing the integer array
for(i=0;i<k;i++)
printf("%d ",a[i]);
return 0;
}
但是当我输入1 2 3 4
时,输出是1 1 1 1
。我想要的只是读取字符串并将输入的字符串的字符转换为整数数组 a[0] = 1 a[1] = 2 a[3]= 3 a[4] = 4
。我可能认为 a[k] = atoi(s)
引用字符串中的第一个元素,而不是其他元素。因此每次迭代都会分配 a[k] = 1
.如何得到想要的结果?
提前致谢。
最佳答案
这可能对你有帮助
#include <stdio.h>
int main() {
const int array_max_size = 100;
char symb;
int arr[array_max_size];
int array_current_size = 0;
do {
scanf("%d%c", &arr[array_current_size++], &symb);
} while (symb != '\n');
// printing array
return 0;
}
关于c - 如何读取空格分隔的整数序列,直到遇到换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326097/