How to read input several lines of integers seperated by spaces (in C++)?











up vote
-3
down vote

favorite












So there are Q lines.
Each line has an arbitrary number of integers separated by spaces, I need to process those numbers.



Example Input



Q = 4
12 32 4 3 2
1 2 3 4
0
2 3 1 223 4 2 3


I am reading each line as string and extracting the numbers as string and then using atoi to convert them to int, ie,



while(Q>0){
for(char c:s){
if (c==' '){
int x = atoi(temp.c_str());
temp = "";
//process x
continue;
}
temp +=c;
}
Q--;
}


Surely there is a better way to do this?



Edit: The numbers of each line are processed differently.



For example, say



Line 1 has 1,2,3,4. Line 2 has 14,15.



Then 1,2,3,4 will be processed differently and 13,14 differently.



This is why I can't use std::cin as it ignores all whitespaces (both spaces and newline).










share|improve this question
























  • I'd just read each line and parse using regex.
    – Ryan Pierce Williams
    Nov 11 at 11:24










  • @RyanPierceWilliams could you please elaborate how to do that?
    – Little_idiot
    Nov 11 at 11:29










  • You could use a regex like this on each line: "([d]+)" to find all integers.
    – Ryan Pierce Williams
    Nov 11 at 11:32










  • Try it out here: regex101.com
    – Ryan Pierce Williams
    Nov 11 at 11:41










  • Is there a pattern on how you process them differently?
    – Andreas DM
    Nov 11 at 12:10















up vote
-3
down vote

favorite












So there are Q lines.
Each line has an arbitrary number of integers separated by spaces, I need to process those numbers.



Example Input



Q = 4
12 32 4 3 2
1 2 3 4
0
2 3 1 223 4 2 3


I am reading each line as string and extracting the numbers as string and then using atoi to convert them to int, ie,



while(Q>0){
for(char c:s){
if (c==' '){
int x = atoi(temp.c_str());
temp = "";
//process x
continue;
}
temp +=c;
}
Q--;
}


Surely there is a better way to do this?



Edit: The numbers of each line are processed differently.



For example, say



Line 1 has 1,2,3,4. Line 2 has 14,15.



Then 1,2,3,4 will be processed differently and 13,14 differently.



This is why I can't use std::cin as it ignores all whitespaces (both spaces and newline).










share|improve this question
























  • I'd just read each line and parse using regex.
    – Ryan Pierce Williams
    Nov 11 at 11:24










  • @RyanPierceWilliams could you please elaborate how to do that?
    – Little_idiot
    Nov 11 at 11:29










  • You could use a regex like this on each line: "([d]+)" to find all integers.
    – Ryan Pierce Williams
    Nov 11 at 11:32










  • Try it out here: regex101.com
    – Ryan Pierce Williams
    Nov 11 at 11:41










  • Is there a pattern on how you process them differently?
    – Andreas DM
    Nov 11 at 12:10













up vote
-3
down vote

favorite









up vote
-3
down vote

favorite











So there are Q lines.
Each line has an arbitrary number of integers separated by spaces, I need to process those numbers.



Example Input



Q = 4
12 32 4 3 2
1 2 3 4
0
2 3 1 223 4 2 3


I am reading each line as string and extracting the numbers as string and then using atoi to convert them to int, ie,



while(Q>0){
for(char c:s){
if (c==' '){
int x = atoi(temp.c_str());
temp = "";
//process x
continue;
}
temp +=c;
}
Q--;
}


Surely there is a better way to do this?



Edit: The numbers of each line are processed differently.



For example, say



Line 1 has 1,2,3,4. Line 2 has 14,15.



Then 1,2,3,4 will be processed differently and 13,14 differently.



This is why I can't use std::cin as it ignores all whitespaces (both spaces and newline).










share|improve this question















So there are Q lines.
Each line has an arbitrary number of integers separated by spaces, I need to process those numbers.



Example Input



Q = 4
12 32 4 3 2
1 2 3 4
0
2 3 1 223 4 2 3


I am reading each line as string and extracting the numbers as string and then using atoi to convert them to int, ie,



while(Q>0){
for(char c:s){
if (c==' '){
int x = atoi(temp.c_str());
temp = "";
//process x
continue;
}
temp +=c;
}
Q--;
}


Surely there is a better way to do this?



Edit: The numbers of each line are processed differently.



For example, say



Line 1 has 1,2,3,4. Line 2 has 14,15.



Then 1,2,3,4 will be processed differently and 13,14 differently.



This is why I can't use std::cin as it ignores all whitespaces (both spaces and newline).







c++ atoi






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 11:32

























asked Nov 11 at 11:21









Little_idiot

12




12












  • I'd just read each line and parse using regex.
    – Ryan Pierce Williams
    Nov 11 at 11:24










  • @RyanPierceWilliams could you please elaborate how to do that?
    – Little_idiot
    Nov 11 at 11:29










  • You could use a regex like this on each line: "([d]+)" to find all integers.
    – Ryan Pierce Williams
    Nov 11 at 11:32










  • Try it out here: regex101.com
    – Ryan Pierce Williams
    Nov 11 at 11:41










  • Is there a pattern on how you process them differently?
    – Andreas DM
    Nov 11 at 12:10


















  • I'd just read each line and parse using regex.
    – Ryan Pierce Williams
    Nov 11 at 11:24










  • @RyanPierceWilliams could you please elaborate how to do that?
    – Little_idiot
    Nov 11 at 11:29










  • You could use a regex like this on each line: "([d]+)" to find all integers.
    – Ryan Pierce Williams
    Nov 11 at 11:32










  • Try it out here: regex101.com
    – Ryan Pierce Williams
    Nov 11 at 11:41










  • Is there a pattern on how you process them differently?
    – Andreas DM
    Nov 11 at 12:10
















I'd just read each line and parse using regex.
– Ryan Pierce Williams
Nov 11 at 11:24




I'd just read each line and parse using regex.
– Ryan Pierce Williams
Nov 11 at 11:24












@RyanPierceWilliams could you please elaborate how to do that?
– Little_idiot
Nov 11 at 11:29




@RyanPierceWilliams could you please elaborate how to do that?
– Little_idiot
Nov 11 at 11:29












You could use a regex like this on each line: "([d]+)" to find all integers.
– Ryan Pierce Williams
Nov 11 at 11:32




You could use a regex like this on each line: "([d]+)" to find all integers.
– Ryan Pierce Williams
Nov 11 at 11:32












Try it out here: regex101.com
– Ryan Pierce Williams
Nov 11 at 11:41




Try it out here: regex101.com
– Ryan Pierce Williams
Nov 11 at 11:41












Is there a pattern on how you process them differently?
– Andreas DM
Nov 11 at 12:10




Is there a pattern on how you process them differently?
– Andreas DM
Nov 11 at 12:10












2 Answers
2






active

oldest

votes

















up vote
1
down vote













#include <iostream>

// ...

int x;
while (std::cin >> x)
; // process x




edited cause of your comment:



#include <iostream>

// ...

int x;
char ch;
while (std::cin >> x >> std::noskipws >> ch >> std::skipws) {
if (ch == 'n')
; // process x differently
}





share|improve this answer























  • cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
    – Little_idiot
    Nov 11 at 11:26












  • @Little_idiot you didn't say so in your question.
    – Swordfish
    Nov 11 at 11:29










  • Sorry fixed it now.
    – Little_idiot
    Nov 11 at 11:42










  • @Little_idiot fixed my answer as well.
    – Swordfish
    Nov 11 at 11:42


















up vote
0
down vote













If you need line oriented parsing and still want to use the power of iostream then I suggest you use std::getline and std::istringstream. Example below



#include <iostream>
#include <sstream>

int main() {
char ch = '';
std::cin >> ch;
if (!std::cin || ch != 'Q') return EXIT_FAILURE;
std::cin >> ch;
if (!std::cin || ch != '=') return EXIT_FAILURE;
int Q = 0;
std::cin >> Q;
if (!std::cin) return EXIT_FAILURE;
std::string line;
std::getline(std::cin, line); // get ready for a new line
while (Q > 0) {
if (!std::getline(std::cin, line)) return EXIT_FAILURE;
std::istringstream iss(line);
int count = 0;
int sum = 0;
int i;
while (iss >> i) {
++count;
sum += i;
}
std::cout << "Found " << count << " integers who's sum was " << sum << 'n';
Q--;
}
std::cout << "Donen";
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248204%2fhow-to-read-input-several-lines-of-integers-seperated-by-spaces-in-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    #include <iostream>

    // ...

    int x;
    while (std::cin >> x)
    ; // process x




    edited cause of your comment:



    #include <iostream>

    // ...

    int x;
    char ch;
    while (std::cin >> x >> std::noskipws >> ch >> std::skipws) {
    if (ch == 'n')
    ; // process x differently
    }





    share|improve this answer























    • cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
      – Little_idiot
      Nov 11 at 11:26












    • @Little_idiot you didn't say so in your question.
      – Swordfish
      Nov 11 at 11:29










    • Sorry fixed it now.
      – Little_idiot
      Nov 11 at 11:42










    • @Little_idiot fixed my answer as well.
      – Swordfish
      Nov 11 at 11:42















    up vote
    1
    down vote













    #include <iostream>

    // ...

    int x;
    while (std::cin >> x)
    ; // process x




    edited cause of your comment:



    #include <iostream>

    // ...

    int x;
    char ch;
    while (std::cin >> x >> std::noskipws >> ch >> std::skipws) {
    if (ch == 'n')
    ; // process x differently
    }





    share|improve this answer























    • cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
      – Little_idiot
      Nov 11 at 11:26












    • @Little_idiot you didn't say so in your question.
      – Swordfish
      Nov 11 at 11:29










    • Sorry fixed it now.
      – Little_idiot
      Nov 11 at 11:42










    • @Little_idiot fixed my answer as well.
      – Swordfish
      Nov 11 at 11:42













    up vote
    1
    down vote










    up vote
    1
    down vote









    #include <iostream>

    // ...

    int x;
    while (std::cin >> x)
    ; // process x




    edited cause of your comment:



    #include <iostream>

    // ...

    int x;
    char ch;
    while (std::cin >> x >> std::noskipws >> ch >> std::skipws) {
    if (ch == 'n')
    ; // process x differently
    }





    share|improve this answer














    #include <iostream>

    // ...

    int x;
    while (std::cin >> x)
    ; // process x




    edited cause of your comment:



    #include <iostream>

    // ...

    int x;
    char ch;
    while (std::cin >> x >> std::noskipws >> ch >> std::skipws) {
    if (ch == 'n')
    ; // process x differently
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 11 at 11:36

























    answered Nov 11 at 11:25









    Swordfish

    8,86511335




    8,86511335












    • cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
      – Little_idiot
      Nov 11 at 11:26












    • @Little_idiot you didn't say so in your question.
      – Swordfish
      Nov 11 at 11:29










    • Sorry fixed it now.
      – Little_idiot
      Nov 11 at 11:42










    • @Little_idiot fixed my answer as well.
      – Swordfish
      Nov 11 at 11:42


















    • cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
      – Little_idiot
      Nov 11 at 11:26












    • @Little_idiot you didn't say so in your question.
      – Swordfish
      Nov 11 at 11:29










    • Sorry fixed it now.
      – Little_idiot
      Nov 11 at 11:42










    • @Little_idiot fixed my answer as well.
      – Swordfish
      Nov 11 at 11:42
















    cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
    – Little_idiot
    Nov 11 at 11:26






    cin ignores all whitespaces by default. I need to separately process integers belonging to each line. Example line 1: 1 2 3 4 line 2: 12 34 Here 1,2,3,4 will be processed differently and 12,34 differently.
    – Little_idiot
    Nov 11 at 11:26














    @Little_idiot you didn't say so in your question.
    – Swordfish
    Nov 11 at 11:29




    @Little_idiot you didn't say so in your question.
    – Swordfish
    Nov 11 at 11:29












    Sorry fixed it now.
    – Little_idiot
    Nov 11 at 11:42




    Sorry fixed it now.
    – Little_idiot
    Nov 11 at 11:42












    @Little_idiot fixed my answer as well.
    – Swordfish
    Nov 11 at 11:42




    @Little_idiot fixed my answer as well.
    – Swordfish
    Nov 11 at 11:42












    up vote
    0
    down vote













    If you need line oriented parsing and still want to use the power of iostream then I suggest you use std::getline and std::istringstream. Example below



    #include <iostream>
    #include <sstream>

    int main() {
    char ch = '';
    std::cin >> ch;
    if (!std::cin || ch != 'Q') return EXIT_FAILURE;
    std::cin >> ch;
    if (!std::cin || ch != '=') return EXIT_FAILURE;
    int Q = 0;
    std::cin >> Q;
    if (!std::cin) return EXIT_FAILURE;
    std::string line;
    std::getline(std::cin, line); // get ready for a new line
    while (Q > 0) {
    if (!std::getline(std::cin, line)) return EXIT_FAILURE;
    std::istringstream iss(line);
    int count = 0;
    int sum = 0;
    int i;
    while (iss >> i) {
    ++count;
    sum += i;
    }
    std::cout << "Found " << count << " integers who's sum was " << sum << 'n';
    Q--;
    }
    std::cout << "Donen";
    }





    share|improve this answer

























      up vote
      0
      down vote













      If you need line oriented parsing and still want to use the power of iostream then I suggest you use std::getline and std::istringstream. Example below



      #include <iostream>
      #include <sstream>

      int main() {
      char ch = '';
      std::cin >> ch;
      if (!std::cin || ch != 'Q') return EXIT_FAILURE;
      std::cin >> ch;
      if (!std::cin || ch != '=') return EXIT_FAILURE;
      int Q = 0;
      std::cin >> Q;
      if (!std::cin) return EXIT_FAILURE;
      std::string line;
      std::getline(std::cin, line); // get ready for a new line
      while (Q > 0) {
      if (!std::getline(std::cin, line)) return EXIT_FAILURE;
      std::istringstream iss(line);
      int count = 0;
      int sum = 0;
      int i;
      while (iss >> i) {
      ++count;
      sum += i;
      }
      std::cout << "Found " << count << " integers who's sum was " << sum << 'n';
      Q--;
      }
      std::cout << "Donen";
      }





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        If you need line oriented parsing and still want to use the power of iostream then I suggest you use std::getline and std::istringstream. Example below



        #include <iostream>
        #include <sstream>

        int main() {
        char ch = '';
        std::cin >> ch;
        if (!std::cin || ch != 'Q') return EXIT_FAILURE;
        std::cin >> ch;
        if (!std::cin || ch != '=') return EXIT_FAILURE;
        int Q = 0;
        std::cin >> Q;
        if (!std::cin) return EXIT_FAILURE;
        std::string line;
        std::getline(std::cin, line); // get ready for a new line
        while (Q > 0) {
        if (!std::getline(std::cin, line)) return EXIT_FAILURE;
        std::istringstream iss(line);
        int count = 0;
        int sum = 0;
        int i;
        while (iss >> i) {
        ++count;
        sum += i;
        }
        std::cout << "Found " << count << " integers who's sum was " << sum << 'n';
        Q--;
        }
        std::cout << "Donen";
        }





        share|improve this answer












        If you need line oriented parsing and still want to use the power of iostream then I suggest you use std::getline and std::istringstream. Example below



        #include <iostream>
        #include <sstream>

        int main() {
        char ch = '';
        std::cin >> ch;
        if (!std::cin || ch != 'Q') return EXIT_FAILURE;
        std::cin >> ch;
        if (!std::cin || ch != '=') return EXIT_FAILURE;
        int Q = 0;
        std::cin >> Q;
        if (!std::cin) return EXIT_FAILURE;
        std::string line;
        std::getline(std::cin, line); // get ready for a new line
        while (Q > 0) {
        if (!std::getline(std::cin, line)) return EXIT_FAILURE;
        std::istringstream iss(line);
        int count = 0;
        int sum = 0;
        int i;
        while (iss >> i) {
        ++count;
        sum += i;
        }
        std::cout << "Found " << count << " integers who's sum was " << sum << 'n';
        Q--;
        }
        std::cout << "Donen";
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 12:40









        Bo R

        601110




        601110






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248204%2fhow-to-read-input-several-lines-of-integers-seperated-by-spaces-in-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly