IT박스

공백 문자가있는 입력에서 문자열을 읽습니까?

itboxs 2020. 8. 30. 07:51
반응형

공백 문자가있는 입력에서 문자열을 읽습니까? [복제]


이 질문에 이미 답변이 있습니다.

Ubuntu를 사용하고 있으며 Geany 및 CodeBlock도 IDE로 사용하고 있습니다. 내가하려는 것은 문자열 (같은 "Barack Obama")을 읽고 변수에 넣는 것입니다.

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    scanf("%s", name);
    printf("Your Name is: %s", name);

    return 0;
}

산출:

Enter your name: Barack Obama
Your Name is: Barack

프로그램이 전체 이름을 읽도록하려면 어떻게해야합니까?


사용하다:

fgets (name, 100, stdin);

100버퍼의 최대 길이입니다. 필요에 따라 조정해야합니다.

사용하다:

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

[]scanset 문자입니다. [^\n]입력이 개행 ( ) 아닌 동안 '\n'입력을받습니다. 그런 다음 %*c입력 버퍼에서 개행 문자를 읽고 (읽지 않음) *입력에서 읽은이 입력이 필요하지 않으므로 버려지고 (할당 억제) 버퍼에있는 개행 문자가 생성되지 않음을 나타냅니다. 취할 수있는 다음 입력에 대한 문제.

여기에서 스캔 세트할당 억제 연산자 에 대해 읽어보십시오 .

사용할 수도 gets있지만 ....

사용하지 마십시오 gets(). 얼마나 많은 문자가 읽어 들일지 미리 데이터를 모르면 알 수없고 gets()버퍼의 끝을지나 문자를 계속 저장 하기 때문에 사용하는 것은 매우 위험합니다. 컴퓨터 보안을 깨는 데 사용되었습니다. fgets()대신 사용하십시오 .


이 시도:

scanf("%[^\n]s",name);

\n 스캔 한 문자열의 구분 기호 만 설정합니다.


다음은 fgets함수 를 사용하여 공백이 포함 된 입력을 얻는 방법의 예입니다 .

#include <stdio.h>

int main()
{
    char name[100];
    printf("Enter your name: ");
    fgets(name, 100, stdin); 
    printf("Your Name is: %s", name);
    return 0;
}

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

str 문자열을 가져 오는 변수입니다.


NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.

#include<stdio.h>
int main()
{
 int i,size;
 char a[100];
 fgets(a,100,stdin);;
 size = strlen(a);
 a[size-1]='\0';

return 0;
}

Update: Updated with help from other users.


#include<stdio.h>
int main()
{
   char name[100];
   printf("Enter your name: ");
   scanf("%[^\n]s",name);
   printf("Your Name is: %s",name);
   return 0;
}

Using this code you can take input till pressing enter of your keyboard.

char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
    scanf("%c ", &ch[i]);
}

#include <stdio.h>
// read a line into str, return length
int read_line(char str[]) {
int c, i=0;
c = getchar();
while (c != '\n' && c != EOF) { 
   str[i] = c;
   c = getchar();
   i++;
}
str[i] = '\0';
return i;
}

If you need to read more than one line, need to clear buffer. Example:

int n;
scanf("%d", &n);
char str[1001];
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",str);

"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;

#include <stdio.h>
int main()
{
    printf("Enter your name\n");
   char a[80];
   gets(a);
   printf("Your name is %s\n", a);
   return 0;
}

The correct answer is this:

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    // pay attention to the space in front of the %
    //that do all the trick
    scanf(" %[^\n]s", name);
    printf("Your Name is: %s", name);

    return 0;
}

That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.


While the above mentioned methods do work, but each one has it's own kind of problems.

You can use getline() or getdelim(), if you are using posix supported platform. If you are using windows and minigw as your compiler, then it should be available.

getline() is defined as :

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

In order to take input, first you need to create a pointer to char type.

#include <stdio.h>
#include<stdlib.h>

// s is a pointer to char type.
char *s;
// size is of size_t type, this number varies based on your guess of 
// how long the input is, even if the number is small, it isn't going 
// to be a problem
size_t size = 10;

int main(){
// allocate s with the necessary memory needed, +1 is added 
// as its input also contains, /n character at the end.
    s = (char *)malloc(size+1);
    getline(&s,&size,stdin);
    printf("%s",s);
    return 0;
}

Sample Input:Hello world to the world!

Output:Hello world to the world!\n

One thing to notice here is, even though allocated memory for s is 11 bytes, where as input size is 26 bytes, getline reallocates s using realloc().

So it doesn't matter how long your input is.

size is updated with no.of bytes read, as per above sample input size will be 27.

getline() also considers \n as input.So your 's' will hold '\n' at the end.

There is also more generic version of getline(), which is getdelim(), which takes one more extra argument, that is delimiter.

getdelim() is defined as:

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);

Linux man page


"%s" will read the input until whitespace is reached.

gets might be a good place to start if you want to read a line (i.e. all characters including whitespace until a newline character is reached).


scanf("%s",name);

use & with scanf input

참고URL : https://stackoverflow.com/questions/6282198/reading-string-from-input-with-space-character

반응형