c - 如何读取空格分隔的整数序列,直到遇到换行符?

标签 c string integer string-formatting

我一直在尝试编写一个程序,该程序将读取一系列空格分隔的整数,直到遇到换行符。我的方法是将输入作为字符串读取,并使用 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/

相关文章:

c++ - 将 PID 缓存到端口映射 Windows 的安全方法

c - MPI 集体通讯

javascript - Angular : BE response token and angular sets it with double quoutes

javascript - 使用 .html() 时,jQuery 会从字符串中去除一些 html 元素吗?

c - 我正在尝试学习如何使用链接列表

CLion Clang-Tidy 使用带符号整数操作数和二进制按位运算符

c - C 字符串的反向数组

java - 为什么Java认为从10到99所有数字的乘积都是0?

java - Integer.valueOf() 和 Autoboxing 之间的性能差异是什么

c++ - 这两个函数的操作顺序是什么