0
2
5
3 4 5 2 1
5
4 4 4 2 1

is the input, where 2 is the number of test cases, 5 is "not" the size of the vector, I have to read the whole line into the vector, but only able to read one line with the code I wrote. Can you suggest better code to read the input?

int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        char c;
        cin>>n;
        getchar();
        vector<int> V;
       while((c = getchar()) != '\n'){ 
            if(atoi(&c)!=0) V.push_back(atoi(&c));
       }
return 0;
}
anfjnlnl
  • 63
  • 7
  • Does your code work ? Do you have any issue with that code ? If yes, please describe ? Or does that code work well, and you just want to know how to improve it ? If yes, in which way do you want to improve it (for example: faster code ? higher performance ? shorter code) ? – Job_September_2020 Jun 20 '21 at 04:47
  • @Job_September_2020 the code only reads first test case but not the second one – anfjnlnl Jun 20 '21 at 04:50
  • Does the first test case include the first 5 lines in your question ? Can you show us the second test case ? Or is it your second test case "5 - 4 4 4 2 1" ? – Job_September_2020 Jun 20 '21 at 04:53
  • I think you can only read integers between 1 to 9. Use `getline` and `sstream` as shown : https://stackoverflow.com/questions/3421817/splitting-int-from-a-string/29326185 – Aditya Singh Rathore Jun 20 '21 at 04:59
  • @Job_September_2020 First test case:"5 -3 4 5 2 1", second test case:"5 - 4 4 4 2 1" – anfjnlnl Jun 20 '21 at 04:59
  • @anfjnlnl, In your function, can you change the variable "char c" to "int a", and then you can use "cin >> a" to read the integer and store it directly into "vector V" ? That way, you don't need to call "getChar()" twice, and don't need to call "atoi()" twice. – Job_September_2020 Jun 20 '21 at 05:06
  • @Job_September_2020 then how can I put a condition for EOF in that case? – anfjnlnl Jun 20 '21 at 05:11

1 Answers1

2
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <limits>
using namespace std;

int main(){
    int t;
    cin >> t;
    while (t--){
        int n, j;
        cin >> n;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        string s;
        getline(cin, s);
        istringstream iss(s);
        vector<int> V;
        while (iss >> j){ 
            V.push_back(j);
       }
    }
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770