簡體   English   中英

如何在C中輸入用換行符分隔的兩個字符串

[英]How to input two strings separated by new line in C

如何輸入用換行符分隔的2個字符串?

我的問題:

首先,我需要給出要獲取的字符串數,然后需要獲取那些字符串,然后顯示出來。

我嘗試了這個:

碼:

#include <stdio.h>
#include <string.h>

int main()
{

    int n,i = 0;
    scanf("%d", &n);
    char arr[n][100];
    for(int i = 0; i < n; i++)
    {
        scanf("%[^\n]s", arr[i]);
    }

    for(int i = 0; i < n; i++)
    {
        printf("%s\n", arr[i]);
    }

    return 0;
}

我的輸入是:

2 I am
Aravind

我的輸出是:

I am
þ

第一行是正確的,但第二行顯示了一些垃圾值。 幫我解決這個問題。

您有兩個主要問題:

  1. "%["格式以結尾的"]"結尾,結尾不應有"s"

  2. "%["格式不會跳過前導空格,就像換行符一樣,它將在您閱讀的第一行之后出現。

通過使用fgets讀取整行代碼,可以輕松解決這兩個問題。

您已經有建議不要使用scanf 但是,如果“必須”使用scanf則可以考慮以下方法:

  • 對於動態內存分配,您應該使用malloc
  • 換行符停留在標准輸入中,因此需要刷新或處理/忽略

這是更新的代碼。

int main()
{
    int n,i = 0;
    scanf("%d", &n);

    scanf("%*[\n]"); 
    /*this will read the \n in stdin and not store it anywhere. So the next call to 
     * scanf will not be interfered with */

    char **inputs;
    inputs = malloc(n * sizeof(char *));

    for (i = 0; i < n; i++)
    {
       inputs[i] = malloc(100 * sizeof(char));
    }


    for(i = 0; i < n; i++)
    {
        scanf("%*[\n]");
        scanf("%100[^\n]", inputs[i]);
    }

    for(i = 0; i < n; i++)
    {
        printf("%s\n", inputs[i]);
    }

    return 0;
}

使用gets(arr [i])代替scanf。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM