c language array about the string problem

deareffen 注册会员
2023-02-27 08:28
把第三行改为scanf("%s %s",&str1,&str2);
把第十三行改为printf("%s %s",str1,str2);
把第十九行改为printf("%s %s",str1,str2);

Hope to adopt

lianmaocc1 注册会员
2023-02-27 08:28

Using commas does not delimit input string.
Using %c to output string is also wrong

dxhdenver 注册会员
2023-02-27 08:28

for reference: < br / >

< div class =" aw - list - img > img

dzkhswz 注册会员
2023-02-27 08:28

Here is my understanding for reference :

1. Because character array names are immutable, it is wrong to assign them. If you want to copy characters in character array, You can use the strcpy() function;

2. Then, using scanf() to get strings using commas makes getting input properly complicated, because scanf() gets strings by default separated by whitespace characters(that is, Spaces, tabs, or newlines), so it can be changed to two %s with or without a space;

3. Print the string in the character array using %s.

4. Finally, add scanf() at the end of the while to get the string to compare next time into the arrays str1 and str2.

Modify as follows: < br / > < br / > reference links: < br / > < a href = "https://baike.baidu.com/item/strcpy/5494519?fr=aladdin" id="textarea_1676975747591_1676975785543_0" rel="noopener noreferrer" target="_blank">


int main(void){
    int k;
    char str1[30],str2[30],str3[30];
    //  https://baike.baidu.com/item/scanf/10773316?fr=aladdin
    scanf("%s %s",str1,str2);  //在scanf()获取字符串不需要使用逗号分隔 
//    printf("s1=%s --- s2=%s\n",str1,str2); 
        // // https://blog.csdn.net/weixin_63279307/article/details/128412296    
            printf("%s %s\n",str1,str2);  // 打印字符数组里的字符串使用%s即可 
        }else if(k<0){

// https://baike.baidu.com/item/strcpy/5494519?fr=aladdin            
            strcpy(str3,str1); // 复制str1中的字符串到str3中 
            strcpy(str1,str2); // 复制str2中的字符串到str2中 
            strcpy(str2,str3); // 复制str3中的字符串到str2中 

            printf("%s %s\n",str1,str2);
        }else if(k==0){
        scanf("%s %s",str1,str2);  // 获取下次需要比较的字符串到字符数组str1和str2中 
    //    printf("s1=%s -- s2=%s\n",str1,str2); 
    return 0;


About the Author

Question Info

Publish Time
2023-02-27 08:28
Update Time
2023-02-27 08:28