简体   繁体   English

C - 为用户输入添加引号

[英]C - Adding quotes to a user input

I want to add quotes to the input given by the user and cannot figure out how. 我想在用户给出的输入中添加引号,但无法弄清楚如何。

printf("Please enter a name: ");
    char string[50];

    scanf ("%[^\n]%*c", string);

After this Id like to be able to add the quotes. 在此之后,Id喜欢能够添加引号。 So if the user types Bob, it is stored as "Bob". 因此,如果用户键入Bob,则将其存储为“Bob”。 Thanks 谢谢

Then, write: 然后写:

string[0] = '"';
scanf ("%[^\n]%*c", string + 1);
size_t len = strlen(string);
string[len] = '"';
string[len + 1] = '\0';

Call scanf() on string + 1 after storing '"' at string[0] . Then obtain the length of the string to add another '"' to its end. string[0]存储'"'后,在string + 1上调用scanf() 。然后获取字符串的长度,在其末尾添加另一个'"'

You can do this 你可以这样做

if(fgets(string,50,stdin)!=NULL){
   char anotherstring[50];
   string[strcspn(string,"\n")]=0;
   int len = (int) strlen(string);
   if(sprintf(anotherstring,"\"%s\"", string) == len+2){
      // anotherstring contains quoted string
   }
}

Here you could have used scanf - you would have to check the return value of scanf to know whether it is successful or not. 在这里你可以使用scanf - 你必须检查scanf的返回值,以了解它是否成功。 Better is to use fgets - it is much easier to work with than scanf . 更好的是使用fgets - 它比scanf更容易使用。

Also if you use scanf you should specify the number of characters that you can read - 此外,如果您使用scanf您应该指定您可以阅读的字符数 -

if(scanf("%49s",string) == 1){
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM