简体   繁体   中英

How To Read String that contains Spaces, in C language

What is the most accurate way to read strings from the keyboard in C, when the string contains spaces in between words? When I use scanf for that purpose then it doesn't read a string with spaces.The second option is to use gets but it is supposed to be harmful(I also want to know why?).Another thing is that I don't want to use any file handling concept like fgets.

These are 2 ways to read strings containing spaces that don't use gets or fgets

  1. You can use getline (POSIX 2008 may not exist in your system) that conveniently manages allocation of the buffer with adequate size to capture the whole line.

     char *line = NULL; size_t bufsize = 0; size_t n_read; // number of characters read including delimiter while ((n_read = getline(&line, &bufsize, stdin)) > 1 && line != NULL) { // do something with line } 
  2. If you absolutely want scanf , in this example it reads to the end of line unless the line has more than the specified number of chars minus 1 for the delimiter. In the later case the line is truncated and you'll get the remaining chars in the next scanf invocation.

     char line[1024]; while (scanf("%1023[^\\n]\\n", line) == 1) { // do something with line } 

I should also point out that when you read strings from the keyboard with scanf for example, you are actually reading from a file with file pointer stdin . So you can't really avoid "any file handling concept"

@user3623265,

Please find a sample program which Uses fgets to read string from standard input.

Please refer some sample C documents as to how fgets can be used to get strings from a keyboard and what is the purpose of stdin.

#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

i = strlen(str) - 1;
if (str[i] == '\n')
    str[i] = '\0';

printf("This is your string: %s", str);
return 0;
}

There is a third option, you can read the raw data from stdin with the read() call:

#include <unistd.h>

int main(void) {
    char buf[1024];
    ssize_t n_bytes_read;

    n_bytes_read = read(STDIN_FILENO, buf, sizeof(buf) - 1);
    if (n_bytes_read < 0) {
        // error occured
    }
    buf[n_bytes_read] = '\0'; // terminte string

    printf("\'%s\'", buf);

    return 0;
}

Please not that every input is copied raw to buf including the trailing return. That is, if you enter Hello World you will get

'Hello World
'

as output. Try online .

If you insist on not having a FILE * in scope, use getchar().

  char buff[1024];
  int ch;
  int i = 0;

  while( (ch = getchar()) != '\n' )
    if(i < 1023)
      buff[i++] = ch;
  buff[i] = 0;

  /* now move string into a smaller buffer */

Generally however it's accepted that stdout and stdin and FILE * are available. Your requirement is a bit odd and, since you are obviously not an advanced C programmer who has an unusual need to suppress the FILE * symbol, I suspect your understanding of C IO is shaky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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