0

First off, i have the .txt file that reads like this:

Abraham Jackson, 10, 15, 10, 13, 8, 18,
Joe Harrier, 13, 4, 5, 27, 12, 14,
Thomas High, 21, 2, 4, 15, 7, 3,
Jeffrey John, 4, 9, 8, 5, 27, 12,
Jason Smith, 3, 25, 8, 7, 4, 13,
$

My code (intended to read data from a .txt file and store it into arrays):

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{

    const int studentsSIZE = 5; 
    string students[studentsSIZE]; 
    string stringscores[30];
    ifstream inputFile;
    inputFile.open("data.txt"); //OPEN THE .TXT FILE
    int k = 0;
    for (int i = 0; i < 5; i++) //READ AND STORE DATAS 
    {
        (getline(inputFile, students[i], ',' )); 
        {
            (getline(inputFile, stringscores[k], ',')); 
            k++;
        }
    }

So far, I've got it to read the .txt file and stored all the names into the array(students) as intended.

My question is how do I remove the \n in the array.

Currently the array is storing the data like this:

{ "Abraham Jackson", "\nJoe Harrier", "\nThomas High", "\nJeffrey John", "\nJason Smith" }

Picture: https://i.stack.imgur.com/PxYxz.png

I have tried by putting inputFile.ignore() before line "(getline(inputFile, students[i], ',' )); " in order to remove the \n, but doing so caused program to remove the very first letter 'A' that it will read from the text file.

{ "braham Jackson", "Joe Harrier", "Thomas High", "Jeffrey John", "Jason Smith" }

G. John
  • 3
  • 4

2 Answers2

0

Check if the first character of a line is equal to '\n' and delete it, if true.

    .....
    for (int i = 0; i < 5; i++) //READ AND STORE DATAS 
    {
        getline(inputFile, students[i], ',' ); 
        if(students[i].size() > 0 && students[i][0] == '\n')
        {
           students[i] = students[i].erase(0,1);
        }
        .......

BTW:

  • Check return values
  • Your read in of the scores won't work correctly.)
Hubi
  • 1,629
  • 15
  • 20
0

getline stops on ',' as you've instructed it to do so. After the last , in a line there is newline character, which has not been captured yet.

Your code is still invalid and will not produce even output you've pasted in question :(

My solution for your problem is either trim username or use extra getline with delimiter \n to capture garbage after the last , in line.

DevilaN
  • 1,317
  • 10
  • 21
  • Thank you for the tips. That code portion that I posted is from a bigger project that I'm working on. I just poorly edited and posted the portion that I got stuck on and did not check if the code would run. – G. John Feb 21 '18 at 09:23