scanf使用space作为行尾

问题描述 投票:0回答:1

对于我的夏季项目,我构建了一个俗气的小加密引擎,我希望有一个功能,用户可以输入字符串/字符串系列,它会在终端中加密它但由于某种原因,程序(我认为它的scanf)是只打印出第一个单词。它可能是我确定用户输入结束的方式,但我认为问题是scanf而不是我的代码(虽然我读过这个并且它让我自己提问)。这是相关的代码:

printf("would you like to [e]ncrypt or [d]ecrypt, or type a word to encrypt\n");
char q[50];
for(int s = 0; s<50; s++){ //initialize string to '0'
    q[s] = '0';
}
scanf("%s \n", q); //reads input from user
for(int s = 0; s<50; s++){ //for loop to read every char and encrypt it
        if(q[s] == '0'){ //'0' determines the end of line
            break;
        }else{  
            union shifter sh = { 0 }; //uses a union to shift the char to unreadable (relatively) char
            sh.str = q[s];
            sh.i += 5;
            printf("%c", sh.str); //prints out chars one at a time
        }

    }
printf("\n"); //new line when done

inb4你们说用户不能输入0,我知道这个,作为一个附带问题,我可以把它初始化为一个不可读的字符

char = 3;

把它作为一个不可读的字符(确切地说是测试结束)

谢谢您的帮助

c scanf
1个回答
0
投票

你的%s只匹配第一个非空白字符串,然后丢弃包含第一个空格后的其他字符。

http://www.cplusplus.com/reference/cstdio/scanf/

© www.soinside.com 2019 - 2024. All rights reserved.