简体   繁体   English

如何在C中输入用换行符分隔的两个字符串

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

How can I input 2 strings which are separated by a new line? 如何输入用换行符分隔的2个字符串?

My Problem: 我的问题:

First I need to give how many strings I need to get and then I need to get those strings then display it. 首先,我需要给出要获取的字符串数,然后需要获取那些字符串,然后显示出来。

I tried this: 我尝试了这个:

Code: 码:

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

My Input is : 我的输入是:

2 I am
Aravind

My Output is: 我的输出是:

I am
þ

First Line I got correct one but second line it shows some garbage value. 第一行是正确的,但第二行显示了一些垃圾值。 Help me to solve this. 帮我解决这个问题。

You have two major problems: 您有两个主要问题:

  1. The "%[" format ends with the closing "]" , there should be no "s" at the end. "%["格式以结尾的"]"结尾,结尾不应有"s"

  2. The "%[" format doesn't skip leading space, like that newline which will be present after the first line you read. "%["格式不会跳过前导空格,就像换行符一样,它将在您阅读的第一行之后出现。

Both these issues can be easily solve by using fgets to read whole lines instead. 通过使用fgets读取整行代码,可以轻松解决这两个问题。

You already have suggestions to not use scanf . 您已经有建议不要使用scanf However, if you 'must' use scanf then you can consider the following approach: 但是,如果“必须”使用scanf则可以考虑以下方法:

  • For dynamic memory allocation you should use malloc 对于动态内存分配,您应该使用malloc
  • the newline character stays in the stdin and hence needs to be flushed or handled/ignored 换行符停留在标准输入中,因此需要刷新或处理/忽略

Here is the updated code. 这是更新的代码。

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