C++에서 std::getline()을 사용하는 방법?
이 기사에서는 C++에서 std::getline() 함수를 사용하는 방법을 살펴보겠습니다. 입력 스트림에서 문자를 읽으려는 경우 매우 편리한 기능입니다.
몇 가지 예시를 통해 이것을 올바르게 사용할 수 있는 방법을 알아봅시다.
C++에서 std::getline()의 기본 구문
이 함수는 입력 스트림에서 문자를 읽고 문자열에 넣습니다.
getline()
이 이 파일의 일부이기 때문에 <string>
헤더 파일을 가져와야 합니다.
이것은 템플릿 인수를 사용하지만 출력이 문자열에 기록되므로 문자열 입력(문자)에 중점을 둘 것입니다.
istream& getline(istream& input_stream, string& output, char delim);
이것이 말하는 것은 getline()
이 입력 스트림을 받아서 출력
에 쓴다는 것입니다. 구분 기호는 delim
을 사용하여 선택적으로 지정할 수 있습니다.
이것은 또한 동일한 입력 스트림에 대한 참조를 반환하지만 대부분의 경우 이 핸들이 필요하지 않습니다.
std::getline()을 사용하여 입력 스트림에서 읽기
기본 구문을 알았으니 이제 std::cin
(표준 입력 스트림)에서 문자열로 입력을 받아보겠습니다.
#include <iostream>
#include <string>
int main() {
// Define a name (String)
std::string name;
std::cout << "Enter the name: ";
// Get the input from std::cin and store into name
std::getline(std::cin, name);
std::cout << "Hello " << name << "!\n";
return 0;
}
산출
Enter the name: JournalDev
Hello JournalDev!
실제로 std::cin
에서 아무 문제 없이 입력을 받을 수 있었습니다!
이제 다음 내용을 포함하는 input.txt
파일이 있는 또 다른 예를 살펴보겠습니다.
$ cat input.txt
Hello from JournalDev
Second Line of file
Last line
이제 파일을 한 줄씩 읽고 문자열 벡터에 저장해 봅시다!
핵심 논리는 입력 스트림이 EOF에 도달할 때까지 std::getline(file)
를 사용하여 계속 읽는 것입니다.
다음 형식을 사용하여 쉽게 작성할 수 있습니다.
std::ifstream infile("input.txt");
// Temporary buffer
std::string temp;
// Get the input from the input file until EOF
while (std::getline(infile, temp)) {
// Add to the list of output strings
outputs.push_back(temp);
}
전체 코드는 다음과 같습니다.
#include <iostream>
#include <string>
#include <vector> // For std::vector
#include <fstream> // For std::ifstream and std::ofstream
int main() {
// Store the contents into a vector of strings
std::vector<std::string> outputs;
std::cout << "Reading from input.txt....\n";
// Create the file object (input)
std::ifstream infile("input.txt");
// Temporary buffer
std::string temp;
// Get the input from the input file until EOF
while (std::getline(infile, temp)) {
// Add to the list of output strings
outputs.push_back(temp);
}
// Use a range-based for loop to iterate through the output vector
for (const auto& i : outputs)
std::cout << i << std::endl;
return 0;
}
산출
Reading from input.txt....
Hello from JournalDev
Second Line of file
Last line
C++에서 std::getline()을 사용하여 구분 기호를 사용하여 입력 분할
또한 delim
인수를 사용하여 getline 함수가 구분 문자로 입력을 분할하도록 할 수 있습니다.
기본적으로 구분 기호는 입니다.\n
(개행). getline()
이 다른 문자를 기반으로 입력을 분할하도록 이것을 변경할 수 있습니다!
위의 예에서 구분 문자를 공백 ' ' 문자로 설정하고 어떤 일이 일어나는지 봅시다!
#include <iostream>
#include <string>
#include <vector> // For std::vector
#include <fstream> // For std::ifstream and std::ofstream
int main() {
// Store the contents into a vector of strings
std::vector<std::string> outputs;
std::cout << "Reading from input.txt....\n";
// Create the file object (input)
std::ifstream infile("input.txt");
// Temporary buffer
std::string temp;
// Get the input from the input file until EOF
while (std::getline(infile, temp, ' ')) {
// Add to the list of output strings
outputs.push_back(temp);
}
// Use a range-based for loop to iterate through the output vector
for (const auto& i : outputs)
std::cout << i << std::endl;
return 0;
}
산출
Reading from input.txt....
Hello
from
JournalDev
Second
Line
of
file
Last
line
실제로 이제 공백으로 구분된 문자열이 생겼습니다!
std::getline() 사용과 관련된 잠재적 문제
std::getline()
은 매우 유용한 함수이지만 std::cin
과 같은 일부 입력 스트림과 함께 사용할 때 직면할 수 있는 몇 가지 문제가 있을 수 있습니다. .
std::getline()
은 선행 공백/개행 문자를 무시하지 않습니다.
이 때문에 getline()
직전에 std::cin >> var;
를 호출하면 입력 변수.
따라서 cin
바로 다음에 getline()
을 호출하면 입력 스트림의 첫 번째 문자이기 때문에 줄 바꿈을 대신 받게 됩니다!
이를 방지하려면 더미 std::getline()
를 추가하여 이 개행 문자를 사용하면 됩니다!
아래 프로그램은 getline()
직전에 cin
을 사용할 때 발생하는 문제를 보여줍니다.
#include <iostream>
#include <string>
int main() {
// Define a name (String)
std::string name;
int id;
std::cout << "Enter the id: ";
std::cin >> id;
std::cout << "Enter the Name: ";
// Notice std::cin was the last input call!
std::getline(std::cin, name);
std::cout << "Id: " << id << std::endl;
std::cout << "Name: " << name << "\n";
return 0;
}
산출
Enter the id: 10
Enter the Name: Id: 10
Name:
이름을 전혀 입력할 수 없었습니다! 후행 줄 바꿈이 입력 스트림에 있었기 때문에 단순히 그것을 취했고 구분 기호이기 때문에 읽기를 멈췄습니다!
이제 실제 std::getline()
바로 앞에 더미 std::getline()
호출을 추가해 보겠습니다.
#include <iostream>
#include <string>
int main() {
// Define a name (String)
std::string name;
int id;
std::cout << "Enter the id: ";
std::cin >> id;
std::cout << "Enter the Name: ";
// Add a dummy getline() call
std::getline(std::cin, name);
// Notice std::cin was the last input call!
std::getline(std::cin, name);
std::cout << "Id: " << id << std::endl;
std::cout << "Name: " << name << "\n";
return 0;
}
산출
Enter the id: 10
Enter the Name: JournalDev
Id: 10
Name: JournalDev
드디어 버그를 수정했습니다! 이것은 std::getline()
을 맹목적으로 사용하기 전에 조금 더 생각하게 되기를 바랍니다.
불행하게도 C++에는 입력을 받을 수 있는 우아한 방법이 없으므로 우리가 가지고 있는 것으로 해결해야 합니다!
결론
이 기사에서는 C++에서 std::getline()을 사용하는 방법에 대해 배웠습니다. 우리는 또한 이 기능의 힘과 함정을 설명하는 몇 가지 예를 살펴봅니다.
참조
- cppreference.com 페이지 std::getline()
- std::getline() 사용에 대한 StackOverflow 질문