简体   繁体   English

Scanf 和 printf 一个包含两个单词的字符串

[英]Scanf and printf a string with two words

I want to make a program to output a string that includes two words using scanf and printf functions.我想制作一个程序来使用scanfprintf函数输出一个包含两个单词的字符串。

This is my source code:这是我的源代码:

#include <stdio.h>
int main () 
{
    char str[20];
    scanf("%s%s", &str);
    printf("%s", str);
    return 0;
}

After I run the code the results are not what I want.运行代码后,结果不是我想要的。

Input:输入:

new version

Output:输出:

new

What is the solution for this problem?这个问题的解决方案是什么?

You can read an entire string including spaces using [^\\n] specifier, which means read everything in the input stream until a newline character is found.您可以使用[^\\n]说明符读取包含空格的整个字符串,这意味着读取输入流中的所有内容,直到找到换行符。

#include <stdio.h>
int main () 
{
    char str[100]; //20 characters is not much, addded a little more
    scanf("%99[^\n]", str); //size limit 99 + null byte
    printf("%s", str);
    return 0;
}

Note that operator & is not needed for char arrays in scanf and the input should be limited to the size of the destination buffer to avoid buffer overflow.请注意, scanf字符数组不需要operator &并且输入应限制为目标缓冲区的大小以避免缓冲区溢出。

A character is 1 byte, in today's machines, generally speaking, that amounts to almost nothing, so be more generous with your char arrays if you can.一个字符是 1 个字节,在今天的机器中,一般来说,这几乎等于零,所以如果可以的话,请对你的char数组更加慷慨。

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

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