有人请解释一下c中的字符串吗?

时间:2013-05-13 07:43:30

标签: c string

如何在没有连接的情况下一个接一个地存储两个字符串(我们可以递增地址)

char str[10];
scanf("%s",str);
str=str+9;
scanf("%s",str);

注意:如果我将第一个字符串作为BALA而第二个字符串作为HI,它应该在BALA之后打印为HI。但HI不应该取代BALA。

4 个答案:

答案 0 :(得分:8)

你不能像这样增加(或以任何其他方式改变)数组,数组变量(str)是一个无法改变的常量。

你可以这样做:

char str[64];

scanf("%s", str);
scanf("%s", str + strlen(str));

这将首先扫描到str,然后立即再次扫描,在第一个字符串的终止'\0'顶部开始新字符串。

如果您先输入"BALA"str的开头将如下所示:

     +---+---+---+---+----+
str: | B | A | L | A | \0 |
     +---+---+---+---+----+

由于strlen("BALA")为4,因此下一个字符串将从上方可见的'\0'顶部开始扫描到缓冲区中。如果您输入"HI",则str将如此开始:

     +---+---+---+---+---+---+----+
str: | B | A | L | A | H | I | \0 |
     +---+---+---+---+---+---+----+

此时,如果您打印str,则会打印为"BALAHI"

当然,这非常危险并可能引入缓冲区溢出,但这就是你想要的。

答案 1 :(得分:2)

如果我理解你想要正确做什么,也许你想把字符串放在一个数组中。 因此,代码的修改版本看起来像

char strings[ARRAY_LENGTH][MAX_STRING_LENGTH];
char* str = strings[0];
scanf("%s",str);
str=strings[1];
scanf("%s",str);

然后打印你需要循环遍历数组的所有字符串,如下所示

int i;
for(i = 0; i < ARRAY_LENGTH; i++)
{
    printf(strings[i]);
}

(您必须定义ARRAY_LENGTH和MAX_STRING_LENGTH)

答案 2 :(得分:0)

可能你正在看这样的事情

    char arr[100] = {0,}, *str = NULL;
    /** initial String will be scanned from beginning **/
    str = arr;

    /** scan first string **/
    fgets(str, 100, stdin);

    /**  We need to replace NULL termination with space is space is delimiter  **/
    str += strlen(str)-1;
    *str = ' ' ;

     /** scan second string from address just after space, 
            we can not over ride the memory though **/

     fgets(str, 100 - strlen(str), stdin);

     printf("%s",arr);

你需要和scanf一样吗

char arr[100] = {0,}, *str = NULL;
/** initial String will be scanned from beginning **/
str = arr;

/** scan first string **/
scanf("%s",str);

/**  We need to replace NULL termination with space is space is delimiter  **/
str += strlen(str);
*str = ' ' ;

/** scan second string from address just after space,
 *                 we can not over ride the memory though **/
str++;
scanf("%s",str);


printf("%s",arr);

答案 3 :(得分:0)

以类似的方向移动,您可以使用%n指令来确定已读取的字节数。不要忘记减去任何前导空格。您可能还需要非常仔细地阅读your manual regarding scanf,但要特别注意“返回值”部分。必须处理返回值以确保实际读取字符串并避免未定义的行为。

char str[64];
int whitespace_length, str_length, total_length;

/* NOTE: Don't handle errors with assert!
 *       You should replace this with proper error handling */
assert(scanf(" %n%s%n", &whitespace_length, str, &total_length) == 1);
str_length = total_length - str_length; 
assert(scanf(" %n%s%n", &whitespace_length, str + str_length, &total_length) == 1);
str_length += total_length - str_length;