如何读取一系列空格分隔的整数,直到遇到换行符? [英] How to read a sequence of space separated integers until newline character is encountered?

查看:214
本文介绍了如何读取一系列空格分隔的整数,直到遇到换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编写一个程序来读取一系列空格分隔的整数,直到遇到换行符。我的方法是将输入作为字符串读取并使用 atoi()将字符串转换为整数。
这是我的方法:

I have been trying to write a program that would read a sequence of space separated integers until the newline character is encountered.My approach was to read the input as a string and using atoi() to convert the string to integer. This is my approach:

#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 。如何获得所需的结果?

But when I enter the input 1 2 3 4 the output is 1 1 1 1. All I want is to read the string and convert the characters of the string entered into terms of an Integer array a[0] = 1 a[1] = 2 a[3]= 3 a[4] = 4.I probably think a[k] = atoi(s) makes the reference to the first element in the string but not others.So every iteration is assigning a[k] = 1.How to get the desired result?

提前致谢。

推荐答案

这可以帮到你

#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;
}

这篇关于如何读取一系列空格分隔的整数,直到遇到换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆