Reading Line by Line From an Input File Into a 2d Array

Reading file into 2nd array, separated by comma

Hi, and so my assignment is to create a French to English translator. My first task is to accept a file and put the chiliad English and French words into a 2nd assortment. The file looks like this:

French k
bonjour,hello
oui,aye
not,no
merci,thanks

I've tried using getline to help me separate the two, but I'm non certain its actually storing anything into the array, because I will demand to sort the array later I create it. When I try to cout the array information technology gives me a memory accost, so I'thou confused on what I need to do.

                          1
2
iii
4
v
6
seven
viii
9
x
eleven
12
13
14
15
16
17
eighteen
nineteen
20
21
22
23
24
25
26
27
28
29
30
31
32
33
                                                      void                            Language::run() {     cord fileName, language, line;     ifstream inFile;                            int                            num;                            //ask user input for file and open file                            //cout << "Proper noun of language file to be read in: ";                            //cin >> fileName;                            inFile.open up(                            "french.txt");                            //inFile.open( fileName.c_str() );                            cout <<                            "File successfully processed!"                            << endl;                            //have Linguistic communication info and number of entries from summit of .txt file                            inFile >> language >> num;                            //create a 2nd assortment for the languages in size of number of entries                            string langArray[2][num];                            for(int                            i = 0; i < ii; i++)     {                            for(int                            j = 0; j < num; j++)         {                            if(getline(inFile,line,                            ','))             {                                  langArray[i][j] = line;                 cout << line <<                            " ";             }         }     } }                                                  

Last edited on

Line sixteen attempts to extract two whitespace-delimited tokens, but your instance only shows 1000, and then each "langArray" line.

The other issue is that yous don't take a continuous streak of comma-delimited tokens. Your bodily sequence, later the 1000, is { word comma word newline word comma word newline ... }

Then you demand to telephone call getline(inFile, line, ',') the first time to become the french word, then call getline(inFile, line) (without the comma delimiter) to get the english language word.

Also, VLAs (Variable-Length Arrays, your line xix) are not standard C++; prefer a vector if the size of the assortment is not known at compile-time.

Last edited on

Hullo false sushi,

This is not valid in C++ string langArray[2][num]; . "num" needs to exist defined as a constant or just utilise 1000. The only way to use this is with a dynamic assortment. Besides information technology should exist string langArray[chiliad][2]; .

I tried to figure out your for loops, but they are wrong and I need some more time to work on information technology.

In the inner for loop you are using the if argument to read the file, but you only read the kickoff office of a line, but not the 2d part. Reading the 2nd part is like the first read, but with out the 3rd parameter in the getline.

I volition load this into something I can test and let you lot know.

Andy

@Handy Andy

I would actually capeesh the help, I met with my tutor and he was saying it was alright just its obviously not. I'yard very new to c++ and this is a data structures and algorithms form thats boot me correct now. I've been looking things up for this and I don't go it.

Maybe your tutor has unlike ideas about how C++ should be taught and likewise what should be used.
Since you are at his mercy stick to his communication and what he wants.
You can learn things properly later.

Howdy simulated sushi,

Since I did non have plenty of your code I created a full program to exam the code. Most of what is in "main" can be copied to your part, merely some may have to reside outside the function.

The comments tell you what I added or inverse. I recollect I got everything.

This is based on what you started with:

                          i
2
three
4
five
half dozen
7
eight
9
10
11
12
13
fourteen
15
sixteen
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fifty
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
                                                      #include <iostream>                            #include <iomanip>                            #include <string>                            #include <limits>                                                        // <--- Added.                            #include <fstream>                            int                            chief() {                            constexpr                            int                            MAXROWS{ 5 }, MAXCOLS{ ii };      std::string fileName, language, french, english;                            // <--- Inverse. Added last 2.                            std::ifstream inFile;                            int                            numRows;                            //ask user input for file and open up file                            //cout << "Name of language file to be read in: ";                            //cin >> fileName;                            inFile.open("french.txt");                            //inFile.open( fileName.c_str() );  // <--- Not needed from C++11 on.                            std::cout <<                            "File successfully processed!"                            <<                            '\n';                            //have Language info and number of entries from pinnacle of .txt file                            inFile >> language >> numRows;     inFile.ignore(std::numeric_limits<std::streamsize>::max(),                            '\due north');                            // <--- Requires header file <limits>. Added.                            //create a 2D assortment for the languages in size of number of entries                            std::cord langArray[MAXROWS][MAXCOLS];                            //for (int i = 0, j = 0; i < numRows && inFile; i++, j = 0)                            //{                            //       if (std::getline(inFile, french, ','))                            //        {                            //            langArray[i][j++] = french;                            //            std::getline(inFile, english);                            //            langArray[i][j] = english;                            //            std::cout << i + i << ". " << french << " " << english << '\n';                            //        }                                                        //}                            for                            (int                            i = 0, j = 0; i < numRows && std::getline(inFile, french,                            ',') && std::getline(inFile, english); i++, j = 0)     {         langArray[i][j++] = french;          langArray[i][j] = english;          std::cout << i + 1 <<                            ". "                            << french <<                            " "                            << english <<                            '\due north';     }      std::cout <<                            "\northward\due north  For checking assortment contents.\northward";                            for                            (int                            row = 0; row < 4; row++)     {           std::cout << row + ane <<                            ". ";                            for                            (int                            col = 0; col < two; col++)         {             std::cout << langArray[row][col] <<                            "  ";         }          std::cout <<                            '\north';     }                            // <--- Keeps panel window open when running in debug mode on Visual Studio. Or a good fashion to pause the program.                            // The next line may not be needed. If you have to printing enter to encounter the prompt information technology is not needed.                            //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\due north');  // <--- Requires header file <limits>.                            std::cout <<                            "\north\northward Press Enter to continue: "; 	std::cin.become();                            return                            0;                            // <--- Not required, only makes a good break point.                            }                        

The for loop was a practiced showtime, merely you are over complicating the whole. The code to a higher place tin can be done in i for loop although information technology is different from a normal for loop.

The if argument is not needed because the reads are done in the for status and therefor the loop will stop when (eof) is set.

There are 2 different for loops and either will work. I left them both and so yous tin can run across the difference.

Lines 54 - 74 I used for testing and are not required or needed. Line 68 on may be useful to y'all in the future.

Andy

Edit:

This produces the output of:

                                      File successfully processed!  // <--- I recall you mean opened. If not it is in the incorrect place.  i. bonjour hello two. oui aye 3. non no four. merci thanks     For checking array contents. 1. bonjour  hello two. oui  yes 3. not  no four. merci  cheers    Press Enter to continue:                                  

Last edited on

I would recommend using a single dimensional array of a struct/course instead of the 2d array. Something like:

                          1
2
3
4
five
half dozen
7
8
9
10
11
12
xiii
14
15
sixteen
17
18
nineteen
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fifty
51
52
53
54
55
56
57
58
59
threescore
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
                                                      #include <iostream>                            #include <vector>                            #include <fstream>                            #include <cord>                            struct                            Translation {     std::string to_translate;     std::string translated; };                            int                            main() {     std::cord fileName, linguistic communication, line;                            int                            num;      std::ifstream inFile("french.txt");                            if(!inFile)     {         std::cerr <<                            "Error opening input file.\n";                            return                            one;     }                            //take Language info and number of entries from top of .txt file                            inFile >> language >> num;                            /*********************************************************************     {         // Using an array, not recommended, see below.         //create an array for the languages in size of number of entries         Translation *translation = new Translation[num];         size_t i = 0;          while(getline(inFile, translation[i].to_translate, ','))         {              getline(inFile, translation[i].translated);             ++i;         }          delete[] translation;     }     ************************************************************************/                            {                            // Using std::vector:                            std::vector<Translation> translation(num);         size_t i = 0;                            // Get the start word from the file.                            while(getline(inFile, translation[i].to_translate,                            ','))         {                            // Read the second give-and-take from the file.                            getline(inFile, translation[i].translated);             ++i;         }     }                            /***********************************************************************     {         // Or using dynamic array of two strings.         std::string(*array)[2] = new std::cord[num][ii];         size_t i = 0;          // Go the first word from the file.         while(getline(inFile, array[i][0], ','))         {             // Read the second word from the file.             getline(inFile, array[i][1]);             ++i;         }          delete[] array;     }     *************************************************************************/                            }                                                  

                                                  
                                                      string langArray[2][num];                        

Unfortunately, this is non standard C++ - although some not-conforming compilers allow it. For standard C++, the size of the assortment has to exist known at compile time. If the size is only known at run-time (such as hither when reading a file), so using a vector instead is the way to go.

                          1
2
iii
iv
5
6
7
8
ix
x
eleven
12
13
xiv
15
16
17
18
nineteen
xx
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
                                                      #include <string>                            #include <fstream>                            #include <iostream>                            #include <vector>                            #include <limits>                            struct                            Translate { 	std::string french; 	std::string english;  	Interpret(const                            std::string& f, std::string& east) : french(f), english(eastward) {} };                            int                            primary() { 	std::ifstream inFile ("french.txt");                            if                            (!inFile.is_open()) { 		std::cout <<                            "File cannot be opened!\due north";                            return                            ane; 	}                            int                            num;  	inFile >> num; 	inFile.ignore(std::numeric_limits<std::streamsize>::max(),                            '\n');  	std::vector<Translate> words; 	words.reserve(num);                            for                            (std::string french, english; std::getline(inFile, french,                            ',') && std::getline(inFile, english language); words.emplace_back(french, english language));                            for                            (const                            auto& west : words) 		std::cout << west.french <<                            '\t'                            << w.english <<                            '\n'; }                        

Even so, every bit the aim is to create a translator then at some point you'll need to look up a French discussion to convert to English. The easiest way to facilitate a look-up like this is to employ a std::map. Consider:

                          i
ii
3
4
5
6
7
8
9
x
eleven
12
13
14
15
xvi
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
                                                      #include <string>                            #include <fstream>                            #include <iostream>                            #include <map>                            #include <limits>                            int                            main() { 	std::ifstream inFile ("french.txt");                            if                            (!inFile.is_open()) { 		std::cout <<                            "File cannot be opened!\n";                            return                            one; 	}                            int                            num;  	inFile >> num; 	inFile.ignore(std::numeric_limits<std::streamsize>::max(),                            '\n');  	std::map<std::string, std::string> words;                            for                            (std::string french, english; std::getline(inFile, french,                            ',') && std::getline(inFile, english language); words[french] = english);                            for                            (const                            auto& west : words) 		std::cout << w.outset <<                            '\t'                            << w.2nd <<                            '\northward';  	std::cout <<                            "\noui is ";                            const                            machine                            w {words.find("oui")};                            if                            (w != words.terminate()) 		std::cout << w->second <<                            '\n';                            else                            std::cout <<                            "<not constitute>\n"; }                        

Topic archived. No new replies immune.

Reading Line by Line From an Input File Into a 2d Array

Source: http://www.cpp.re/forum/beginner/273705/

0 Response to "Reading Line by Line From an Input File Into a 2d Array"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel