while not '\n'

This is a discussion on while not '\n' within the C++ Programming forums, part of the General Programming Boards category; suppose you will get the average of N numbers. the input would just be the N numbers e.g. 1 2 ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    91

    while not '\n'

    suppose you will get the average of N numbers.
    the input would just be the N numbers

    e.g.

    1 2 3 4
    2.5

    1 2 3 4 5
    3

    my problem is how to terminate when the enter is pressed.


    Code:
    while ( \* right code *\ != '\n' )
    {
       cin >> x;
       ave+=x;
       n++;
    }
    cout<< ave/n;

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    You should use std::getline for that:
    getline - C++ Reference

    First read a line, then parse it...
    To be honest I consider this to be one great weakness in the C++ streams. I used to be a C coder, and I just never got the hang of those C++ streams, even though I know most of the stl....

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    theres 2 ways to do this that come to mind.

    one of them involve stdio.h

    (the main idea is that you know how many numbers (N) there are)
    Code:
    #include <stdio.h>
    
    const int n = 5;
    
    int main()
    {
    
    double avg;
    for(int i=0;i<n;++i)
    {
      int input;
      scanf("%d", &input);
      avg+=input;
    }
    avg=avg/n;
    printf("%f",avg);
    
    return 0;
    }
    and

    Code:
    #include <iostream>
    #include <sstream>
    #include <string>
    
    using namespace std;
    
    const int n = 5;
    
    int main()
    {
    
    string input;
    double avg;
    getline(cin,input);
    istringstream iss(input);
    for(int i=0;i<n;++i)
    {
      int token;
      iss >> token;
      avg+=token;
    }
    avg = avg / n;
    
    cout << avg;
    
    return 0;
    }

    ...now I guess if you dont know N before hand..

    try this, im not 100% this is correct though

    Code:
    #include <iostream>
    #include <sstream>
    #include <string>
    
    using namespace std;
    int main()
    {
    int n = 0;
    string input;
    double avg;
    getline(cin,input);
    istringstream iss(input);
    
    int token;
    while(  iss >> token )
    {
      avg+=token;
      ++n;
    }
    avg = avg / n;
    
    cout << avg;
    
    return 0;
    }
    EDIT: i tried it, it works
    Last edited by rodrigorules; 02-23-2010 at 05:04 AM.

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    @rodrigorules:
    If you wouldn't have forgotten to initialize "avg" to 0 it would even be legal C++ code :P (I think, that's the only bug I can spot by just looking at it for a few seconds).

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21