📌  相关文章
📜  C程序从空格分隔的整数序列输入数组

📅  最后修改于: 2021-05-28 04:15:30             🧑  作者: Mango

给定一个由空格分隔的整数组成的字符串S ,任务是编写一个C程序,将整数作为字符串S的输入,并将它们存储在数组arr []中

例子:

方法:解决给定问题的想法是使用getchar()函数检查在接受输入时是否找到了’\ n’(换行符),然后停止输入。请按照以下步骤解决给定的问题:

  • 初始化一个变量,例如count ,该变量用于存储数组元素的索引。
  • 初始化大小为10 6的数组arr []以将元素存储到数组中。
  • 使用do-while循环进行迭代,直到出现newLine并执行以下步骤:
    • 将当前值存储在索引计数scanf(“%d”,&arr [count]);中。并增加count的值。
    • 如果下一个字符不是endline ,则继续。否则,请跳出循环。
  • 完成上述步骤后,打印存储在数组中的元素。

下面是上述方法的实现:

C
// C program for the above approach
#include 
  
// Driver Code
int main()
{
    // Stores the index where the
    // element is to be inserted
    int count = 0;
  
    // Initilaize an array
    int a[1000000];
  
    // Perform a do-while loop
    do {
  
        // Take input at position count
        // and increment count
        scanf("%d", &a[count++]);
  
        // If '\n' (newline) has occured
        // or the whole array is filled,
        // then exit the loop
  
        // Otherwise, continue
    } while (getchar() != '\n' && count < 100);
  
    // Resize the array size to count
    a[count];
  
    // Print the array elements
    for (int i = 0; i < count; i++) {
        printf("%d, ", a[i]);
    }
  
    return 0;
}


输出:

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。