Strings and input

NOTE: This article is part of a C++ guide, therefore only C++ code will be displayed.

Getting a whole line as a string

string line;
getline(cin >> ws, line);

// example
int main(){
    // test cases
    int tc;
    cin >> tc;
    for(int testcase = 0;testcases < tc;testcases++){
        string line;
getline(cin >> ws, line);
        // ...
    }
}

Split Function

vector<string> split (string s, char delim) {
    vector<string> result;
    stringstream ss(s);
    string item;

    while (getline (ss, item, delim)) {
        result.push_back(item);
    }

    return result;
}

// example
int main(){
    // test cases
    int tc;
    cin >> tc;
    for(int testcase = 0;testcases < tc;testcases++){
        string line;
        getline(cin >> ws, line);
        // here ' ' means it splits by spaces
        // this could be any character (example ',')
        vector<string> words = split(line,' ');
    }
}
Copied to Clipboard