I / O - C字符串的操作

时间:2014-12-31 04:00:18

标签: c string io

我希望迭代一个字符串(由用户输入),在每个字符后面返回输入的字符串(即" Hello" - >" H ello"。

如果我预设 str 的值(即char str [] =" Hello&#34 ;;)则会打印出所需的结果(" H ello&#34 ;),但用户输入不是这样(即如果用户输入" Hello"输出是" H")。如何根据用户输入成功提取和操作C字符串?

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

int main()
{
    char str[] = "";
    printf("\nEnter a string: ");
    scanf("%s", &str);

    printf("\nYou typed: %s \n", str);  

    int i = 0;
    char newstr[150] = "";

    for (i = 0; i < strlen(str); i++)
    {
        newstr[2*i] = str[i];
        newstr[2*i+1] = ' ';
    }

    newstr[2 * strlen(str)] = '\0';


    printf("\nExpanded String: ");
    printf("%s", newstr);

    return 0;
}

3 个答案:

答案 0 :(得分:1)

下面:

char str[] = "";

从初始化器推断出str的大小,在这种情况下,初始化器大一个字节。因此str不能保存大于一个字节的字符串,并且由于零终止符是一个大字节,因此没有更多的空间用于有效负载。修复是指定大小:

char str[1024] = "";

现在str有足够的空间容纳一千字节的数据,或者除了终结符之外还有1023个字符。故意选择尺寸远大于您期望的输入。

除此之外,最好通过在格式字符串中包含大小来阻止scanf写入缓冲区的末尾。那是

scanf("%1023s", str); // now scanf will not read more than 1023 bytes plus sentinel.

...反过来,相应地增加newstr的大小(为str的两倍)是个好主意,即

char newstr[2047]; // 2 * 1023 + terminator

......或者,你知道,根据你想要支持的字符串的长度,使str变小。

感谢Cool Guy抓住多余&newstr尺寸的影响。

答案 1 :(得分:0)

如何根据用户输入成功提取和操作C字符串?

您可以改用getchar()。

例如,您可以先将用户输入存储在数组中。然后问题变得和你的'char str [] =“Hello”:

一样
int index = 0
while((temp1 = getchar())!= '\n'){
    str[index++] = temp1;
}

答案 2 :(得分:0)

the following code 
-complies cleanly
-checks and handles errors
-does the job
-doesn't use unneeded memory
 (well actually) the logic could be a loop
 that reads one char, outputs char, outputs space
 or something similar if a trailing space is a problem
 then the input buffer could be a single character

#include <stdio.h>
#include <stdlib.h> // exit, EXIT_FAILURE
#include <string.h>

int main()
{
    // char str[] = "";
    // there actually has to be room for the string
    char str[100] = {'\0'};

    printf("\nEnter a string: ");
    if( 1 != scanf("%s", str) ) // arrays degenerate to pointer so no extra '&' needed
    { // then scanf failed
        perror( "scanf failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("\nYou typed: %s \n", str);

    // there is no need to keep the modified string in memory
    // when all that will be done is print it
    int i = 0; // loop counter

    printf("\nExpanded String: ");

    for (i = 0; i < strlen(str); i++)
    {
        printf("%c", str[i]);

        if( i < (strlen(str)-1) )
        { // then another char will follow
            printf( " " );
        }

        else
        {
            printf( "\n" );
        } // end if
    } // end for

    return 0;
} // end function: main