使用空间作为行尾的scanf

时间:2018-08-30 21:40:25

标签: c scanf

对于我的暑期项目,我构建了一个俗气的小加密引擎,我希望拥有一个功能,用户可以输入字符串/字符系列,并且可以在终端中对其进行加密,但是出于某种原因,该程序(我认为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;

并将其作为不可读的字符(确切地说是测试结束)

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您的%s仅匹配非空格字符的第一个字符串,然后丢弃其他字符,包括第一个空格。

请参阅http://www.cplusplus.com/reference/cstdio/scanf/

相关问题