0

How to separate 2 inputs(with spaces) into 2 arrays in c++

I tried to do one input like this but adding another input is very long: #include <iostream> using namespace std; bool isNumber(string str) { int i = 0; if (str[0] == '-') { i++; } for (; i < str.length(); i++) { if (!isdigit(str[i])) { return false; } } return true; } int findLengthOfInput(string input) { int n = 1; int k = 0; while (input[k] == ' ') { k++; } string word; for (; k < input.length(); k++) { if (input[k] == ' ') { if (!isNumber(word)) { continue; } while (input[k] == ' ') { k++; } n++; word = ""; } word += input[k]; } if (!isNumber(word)) { n = 0; } return 0; } int main() { // First input string input; int n = 0; do { cout << "Enter the first input? "; cin >> input; string input2; getline(cin, input2); input = input + input2; // Find number of items in input n = findLengthOfInput(input); } while (n != 2); // Separate input int j = 0; string arr[2]; while (input[j] == ' ') { j++; } for (int i = 0; i < 2; i++) { string word = ""; for (; j < input.length(); j++) { if (input[j] == ' ') { while (input[j] == ' ') { j++; } break; } word += input[j]; } arr[i] = word; } // Some code }

2nd Jun 2024, 3:19 AM
Mitpro
Mitpro - avatar
3 Antworten
+ 2
Can you give some input examples and how they should be stored in the array? I didn't clearly understand the code intention here. And what that isNumber() is for? like to ignore anything looking like numbers? what if the numeric string contains floating point value e.g, "123.456" - with decimal point? should those be ignored as well?
2nd Jun 2024, 7:48 AM
Ipang
+ 1
In c++ 20, this can be done in one line just by using the std::ranges::split view. Pls check the documentation for additional information
2nd Jun 2024, 5:28 AM
RuntimeTerror
RuntimeTerror - avatar
+ 1
Mitpro there is a bug in findLengthOfInput(). It always returns 0. It should return n. If the purpose of the program is simply to input two numbers separated by spaces, then let cin do the work. It will read numbers and skip spaces for you. For example: #include <iostream> using namespace std; int main() { int n[2]; cin >> n[0] >> n[1]; cout << n[0] << ", " << n[1]; return 0; } Input: -24 50 Output: -24, 50
2nd Jun 2024, 2:15 PM
Brian
Brian - avatar