简体   繁体   English

C编程 - 在字符串中获取多个单词

[英]C Programming — get multiple words in string

I am trying to get a full sentence eg. 我试图得到一个完整的句子,例如。 "This is a sentence." “这是一句话。” to be stored in the global variable string named 'global'. 存储在名为'global'的全局变量字符串中。 It will then print out the sentence back out. 然后它将打印出来的句子。 However after entering my input, I can only get the first word of the sentence printed (This). 输入我的输入后,我只能得到打印句子的第一个单词(This)。 Anyone got any ideas? 有人有任何想法吗?

#include <string.h>

char** global;

int main () {

    printf("Please Enter Text: \n");
    scanf("%s", &global);

    printf("%s", &global);


    return 0;
}

The char** global should be char* global only. char** global应该只是char* global

& with printf is not required. &printf不是必需的。

You need to use fgets(var_name,no_of_chars,FILE*) in place of scanf . 您需要使用fgets(var_name,no_of_chars,FILE*)代替scanf

fgets(global,100,stdin); //where global is char global[100]; 

Example : 示例:

Use of gets is more serious then i was thinking. 使用gets比我想的更严重。 So it's no longer recommended. 所以不再推荐了。

A Better one 一个更好的

char global[100];    
int main () {
    printf("Please Enter Text: \n");
    if(fgets(global,50,stdin)) //It will take Maximum 50 chars. So no buffer overflow. 
    fputs(global,stdout);
    return 0;
}

Your variable char **global; 你的变量char **global; is a disaster zone. 是一个灾区。 It is a null pointer. 它是一个空指针。 It must be made to point to some valid data before it can be used. 必须先使用一些有效数据才能使用它。 It is a double pointer, in fact, so you have to make space available like this: 事实上,这是一个双指针,所以你必须像这样提供空间:

char array[1000];
char *pointer = array;
char **global = &pointer;

Now you could safely use global[0] . 现在你可以安全地使用global[0]

Inside the function, you pass &global to scanf() ; 在函数内部,您将&global传递给scanf() ; that is a char *** . 这是一个char *** Being a 'Three-Star Programmer' is not a good thing, especially when you do it by accident and not by design. 成为“三星级程序员”并不是一件好事,特别是当你偶然而非设计时。

You include the header <string.h> but don't use any of its functions. 您包含头<string.h>但不使用其任何功能。 You do use functions from <stdio.h> and you don't include that. 您确实使用了<stdio.h>函数,但您没有包含它。 Technically, you invoke undefined behaviour by using the variadic functions printf() and scanf() without a function prototype in scope. 从技术上讲,通过使用variadic函数printf()scanf()而不使用范围中的函数原型来调用未定义的行为。 The compiler is entitled to be told about functions that take a variable number of arguments (that's what 'variadic' means), and is entitled to miscompile code where it is not told that the function is variadic. 编译器有权被告知具有可变数量参数的函数(即'variadic'意味着什么),并且有权在不告知该函数是可变参数的情况下错误编译代码。

Assuming you really do need a global variable at all (they're generally not a good idea and you should avoid using them as much as possible), then you could reasonably write: 假设你确实需要一个全局变量(它们通常不是一个好主意,你应该尽可能避免使用它们),那么你可以合理地写:

#include <stdio.h>

char global[1000];

int main(void)
{
    printf("Please Enter Text: ");
    if (scanf("%s", global) == 1)
        printf("%s\n", global);
    return 0;
}

This is at least sound code, but it still has your original problem that it reads only one word, not a whole line. 这至少是声音代码,但它仍然有你原来的问题,它只读一个字,而不是整行。

Forget that gets() exists. 忘了gets()存在。 It was one of the buggy functions used in the first Internet Worm of 1988 (Google for 'morris internet worm'). 它是1988年第一个互联网蠕虫(谷歌的'莫里斯互联网蠕虫')中使用的错误功能之一。 It is irredeemable; 它是无法挽回的; it cannot be used safely in a hostile environment, and all programming has to be done assuming a hostile environment. 它不能在恶劣的环境中安全使用,所有编程都必须在恶劣的环境中完成。

To read a line, use fgets() . 要读取一行,请使用fgets()

#include <stdio.h>
#include <string.h>

char global[1000];

int main(void)
{
    printf("Please Enter Text: ");
    if (fgets(global, sizeof(global), stdin) != NULL)
    {
        size_t len = strlen(global);
        if (len != 0 && global[len-1] == '\n')
            global[--len] = '\0';
        printf("%s\n", global);
    }
    return 0;
}

This gets a line of data into global . 这会将一行数据导入global

You can legitimately ask how len could ever be zero (I asked it of myself, and I replaced assert(len != 0) because of the answer). 你可以合理地询问len怎么可能为零(我问自己,我因为答案而取代了assert(len != 0) )。 One answer would be 'standard input was redirected from a binary file and the first byte was a null (zero) byte'. 一个答案是'标准输入从二进制文件重定向,第一个字节是空(零)字节'。 Then fgets() would read data including the null byte up to the first newline, but the strlen() would stop at the null byte, reporting 0 as the length. 然后fgets()将读取包括空字节直到第一个换行符的数据,但是strlen()将停止在空字节处,报告0作为长度。

The code removes the newline from the string, and determines its length at the same time — you normally need that length. 代码从字符串中删除换行符,并同时确定其长度 - 通常需要该长度。 It then prints it. 然后它打印出来。 Notice that the code checks that fgets() succeeded. 请注意,代码检查fgets()成功。 I/O (especially input) has a habit of breaking when you aren't looking. I / O(尤其是输入)在你不看的时候有一种破坏的习惯。 A lot of the time, it will work fine, but to make your program robust, you have to be paranoid about input operations failing (and, later, memory allocations failing). 很多时候,它会工作正常,但为了使你的程序健壮,你必须对输入操作失败(以及之后,内存分配失败)的偏执。

Are you looking for something like this:- 你在寻找这样的东西: -

 scanf("%[^\t\n]",&global);

Also in your printf & is not required. 也在你的printf &不是必需的。 It should be like: 应该是这样的:

printf("%s", global);

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

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