How to read a line of numeric data, put in an array to sort it with quick sort? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to read a line of numeric data, put in an array to sort it with quick sort?

Iā€™m a noob in c++ so I might make a lot of flaws here. Ok, so I have a text file called ā€œnumbersā€. It has the following data: 0 1 34 67 89 2 23 4 5 Based on a code from a cpp tutorial, I was able to read the file and print it: #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string line; ifstream myfile ("numbers.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); } else cout << "Unable to open file"; return 0; } Good, so now I desire to use a quick sort (Iā€™m prohibited to use bubble sort in this exercise) to print the numbers in ascending order. The problem behind it is that, for it to work, I need to put each data from the line into an array for it to be sortable. Based on the reading file code, how can I put each data in an array so that I can sort it? Iā€™ve read some resources online but they use a lot of ā€œstd::ā€ which doesnā€™t seem similar to the reading file code that Iā€™m using.

23rd Oct 2018, 3:28 AM
ManukaServer
ManukaServer - avatar
1 Answer
+ 3
You can change while (getline(<...>)) to while (myfile >> val) - where val is an int variable. This way, each number in the file is assigned to val for each iteration of the loop, instead of just assigning the whole line to std::string line. In the loop body, assign val to it's corresponding element of the array: // Detail omitted. while (myfile >> val) { int[i] = val; i++; } Online resources typically write std:: 'cause it's the full form and also the formal way to access anything in the std namespace. You already written "using namespace std;" in your code so you can remove std in your code, though I don't recommend that.
23rd Oct 2018, 4:03 AM
HoĆ ng Nguyį»…n Văn
HoĆ ng Nguyį»…n Văn - avatar