C를 사용하여 키보드에서 문자열을 읽는 방법?
사용자가 입력한 문자열을 읽고 싶다.줄의 길이를 모른다.C에는 끈이 없으므로 나는 포인터를 다음과 같이 선언했다.
char * word;
그리고 사용scanf
키보드에서 입력을 읽으려면:
scanf("%s" , word) ;
분할 결함을 찾았어
길이를 알 수 없는 경우 C의 키보드에서 입력을 읽으려면 어떻게 해야 하는가?
다음에 대해 할당된 스토리지가 없는 경우word
- 매달린 포인터일 뿐이다.
변경:
char * word;
다음으로:
char word[256];
여기서 256은 임의의 선택이라는 점에 유의하십시오. 이 버퍼의 크기는 가능한 최대 문자열보다 커야 합니다.
또한 fgets가 더 나은 (세이퍼) 옵션으로, 임의 길이 문자열을 읽기 위해 scanf를 스캔하는 것이 더 낫다는 점에 유의하십시오.size
다시 버퍼 오버플로를 방지하는 데 도움이 되는 인수:
fgets(word, sizeof(word), stdin);
길이를 모르는 파일(stdin 포함)에서 입력을 읽을 때는 종종 사용하는 것이 좋다.getline
보다는scanf
또는fgets
때문에getline
입력한 문자열을 수신하기 위한 null 포인터를 제공하는 한 문자열에 대한 메모리 할당을 자동으로 처리한다.이 예는 다음을 예시한다.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
ssize_t read;
printf ("\nEnter string below [ctrl + d] to quit\n");
while ((read = getline(&line, &len, stdin)) != -1) {
if (read > 0)
printf ("\n read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);
printf ("Enter string below [ctrl + d] to quit\n");
}
free (line); /* free memory allocated by getline */
return 0;
}
관련 부품:
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);
설정line
로NULL
getline이 자동으로 메모리를 할당하게 한다.출력 예:
$ ./getline_example
Enter string below [ctrl + d] to quit
A short string to test getline!
read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!
Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL
read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL
Enter string below [ctrl + d] to quit
그래서 ~와 함께.getline
사용자의 문자열이 얼마나 길지 추측할 필요가 없다.
사용할 권장 사항이 있는 이유를 알 수 없다.scanf()
여기에scanf()
형식 문자열에 제한 매개 변수를 추가하는 경우에만 안전함(예:%64s
그럭저러
훨씬 더 좋은 방법은 사용하는 것이다.char * fgets ( char * str, int num, FILE * stream );
.
int main()
{
char data[64];
if (fgets(data, sizeof data, stdin)) {
// input has worked, do something with data
}
}
(테스트되지 않음)
그것을 사용하기 위해서는 포인터가 있어야 한다.
다음 코드 사용:
char word[64];
scanf("%s", word);
이것은 1964년의 문자열을 만들고 그것에 대한 입력을 읽는다.입력이 64바이트보다 길면 워드 어레이가 오버플로되고 프로그램을 신뢰할 수 없게 된다는 점에 유의하십시오.
옌스가 지적했듯이 현을 읽을 때는 scanf를 사용하지 않는 것이 좋을 것이다.이것은 안전한 해결책이 될 것이다.
char word[64]
fgets(word, 63, stdin);
word[63] = 0;
#include<stdio.h>
int main()
{
char str[100];
scanf("%[^\n]s",str);
printf("%s",str);
return 0;
}
입력: 문자열 읽기
ouput: 문자열 인쇄
이 코드는 위와 같이 간격이 있는 문자열을 출력한다.
다음 코드는 사용자의 입력 문자열을 읽을 때 사용할 수 있다.하지만 공간은 64개로 제한되어 있다.
char word[64] = { '\0' }; //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
scanf_s("%c", &word[i++], 1);
}
참조URL: https://stackoverflow.com/questions/7709452/how-to-read-string-from-keyboard-using-c
'IT이야기' 카테고리의 다른 글
vuejs - 동적 입력 'synamic' (0) | 2022.05.08 |
---|---|
Java: 인스턴스(Instanceof) 및 제네릭 (0) | 2022.05.08 |
math.h를 포함함에도 불구하고 C에서 pow()에 대한 정의되지 않은 참조 (0) | 2022.05.08 |
Vuejs2: 감시자를 어떻게 파괴할 수 있을까? (0) | 2022.05.08 |
로거의 다른 레벨을 다른 대상에 기록하도록 Logback을 구성하는 방법 (0) | 2022.05.07 |