티스토리 뷰

■ C++

자주쓰지만 까먹는 것들

2023. 11. 23. 08:33

띄어쓰기로 string 분리 저장하기

    std::string sentence = "Hello world! This is a sentence.";
    std::vector<std::string> words;

    // stringstream을 사용하여 string을 띄어쓰기로 분리
    std::stringstream ss(sentence);
    std::string word;
    while (ss >> word) {
        words.push_back(word);
    }

특정 구분자로 string 분리 저장하기

    string str = "apple,banana,orange";
    vector<string> vec;
    stringstream ss(str);
    string token;
    while(getline(ss,token,','))
        vec.push_back(token);
    for(const auto& ele : vec)
        cout << ele << endl;

파일 열어서 쓰기

    char arr[]= "Hello, World!";
    std::ofstream file("output.txt");
    if (file.is_open()) {
        file << arr;
        file.close();
    }

파일 열어서 읽어오기

ifstream file("input.txt");
vector<string> row;
if(file.is_open())
{
    string str;
    while(getline(file,str))
    {
        row.push_back(str));
    }
    file.close();    

'■ C++' 카테고리의 다른 글

함수 오버로딩(Function Overloading)  (0) 2023.04.04
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함