Solved

# need help with a loop and aray

Posted on 2004-10-19
224 Views
i neeed help writting a program that asks the user to input 10 integers tests to make sure it is an integer and assorts it in assending order if they ener a invalid number ask them to reenter it

i need help with this and it is urgent so anyone that can help me with this i would gatelly appreciate it

thanks
ted
0
Question by:tedschnieders
• 2

LVL 86

Expert Comment

ID: 12349570
#include <list>
#include <iostream>
using namespace std;

int n;
string str;
while (1) {

cout << "Enter an integer: " << endl;

getline(cin,str);

char* pc;
n = (int) strtol(str.c_str(),&pc,10);

if (*pc) { // conversion error, not a valid int

cout << "Invalid number" << endl;

} else break; // terminate loop
}

return n;
}

int main () {

list<int> lst;
int n;

for ( int i = 0; i < 10; ++i) {

lst.push_back(n);
}

lst.sort();

for ( list<int>::iterator it = lst.begin(); it != lst.end; ++it) {

cout << *it << endl;
}
}
0

Author Comment

ID: 12349737
thank you for responding so quickly

i want them to enter one number at a time and store them in a array 0 - 9
0

LVL 86

Accepted Solution

jkr earned 500 total points
ID: 12349889
Oh, in this case, you could use

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int compare( const void *arg1, const void *arg2 ) {

int n1, n2;

n1 = (int) arg1;
n2 = (int) arg2;

if ( n1 < n2) return -1;

if ( n1 > n2) return 1;

return 0;
}

int n;
string str;
while (1) {

cout << "Enter an integer: " << endl;

getline(cin,str);

char* pc;
n = (int) strtol(str.c_str(),&pc,10);

if (*pc) { // conversion error, not a valid int

cout << "Invalid number" << endl;

} else break; // terminate loop
}

return n;
}

int main () {

int arr[10];
int n;

for ( int i = 0; i < 10; ++i) {

}

qsort(arr,10,sizeof(int),compare);

for ( i = 0; i < 10; ++i) {

cout << arr[i] << endl;
}
}
0

## Featured Post

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generatâ€¦
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on thâ€¦
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.