C++ Read String in File Into 2d Array

Reading file into 2d array, separated by comma

Hi, then my assignment is to create a French to English translator. My get-go job is to have a file and put the 1000 English language and French words into a second array. The file looks like this:

French 1000
bonjour,hello
oui,yes
non,no
merci,thanks

I've tried using getline to aid me separate the two, but I'm not sure its actually storing anything into the assortment, because I volition demand to sort the array afterward I create information technology. When I try to cout the array information technology gives me a memory address, so I'yard confused on what I need to practise.

                          i
2
iii
4
v
half dozen
seven
8
9
x
eleven
12
thirteen
xiv
xv
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
                                                      void                            Language::run() {     string fileName, language, line;     ifstream inFile;                            int                            num;                            //ask user input for file and open up file                            //cout << "Name of language file to exist read in: ";                            //cin >> fileName;                            inFile.open up(                            "french.txt");                            //inFile.open up( fileName.c_str() );                            cout <<                            "File successfully candy!"                            << endl;                            //accept Linguistic communication info and number of entries from height of .txt file                            inFile >> language >> num;                            //create a 2nd array for the languages in size of number of entries                            string langArray[two][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 16 attempts to extract ii whitespace-delimited tokens, but your example only shows 1000, and and then each "langArray" line.

The other upshot is that you don't have a continuous streak of comma-delimited tokens. Your actual sequence, after the thousand, is { word comma word newline word comma discussion newline ... }

So you lot need to call getline(inFile, line, ',') the first time to get the french word, and and so call getline(inFile, line) (without the comma delimiter) to get the english word.

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

Last edited on

Hello fake sushi,

This is not valid in C++ string langArray[2][num]; . "num" needs to exist defined as a constant or simply use 1000. The only way to use this is with a dynamic array. Also information technology should be string langArray[one thousand][ii]; .

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

In the inner for loop y'all are using the if argument to read the file, simply you merely read the commencement office of a line, but not the second office. Reading the second office is like the starting time read, merely with out the 3rd parameter in the getline.

I volition load this into something I can examination and let yous know.

Andy

@Handy Andy

I would really capeesh the aid, I met with my tutor and he was saying it was alright but its obviously non. I'thou very new to c++ and this is a information structures and algorithms class thats kicking me right now. I've been looking things upward for this and I don't become it.

Perchance your tutor has different ideas well-nigh how C++ should be taught and also what should be used.
Since yous are at his mercy stick to his advice and what he wants.
You lot can learn things properly afterwards.

Howdy imitation sushi,

Since I did not have plenty of your code I created a full programme to test the code. Most of what is in "main" can be copied to your function, but some may have to reside outside the function.

The comments tell you what I added or changed. I remember I got everything.

This is based on what you started with:

                          1
2
3
4
v
6
vii
8
9
10
eleven
12
thirteen
xiv
xv
sixteen
17
eighteen
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
50
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                            main() {                            constexpr                            int                            MAXROWS{ 5 }, MAXCOLS{ 2 };      std::string fileName, language, french, english;                            // <--- Changed. Added last 2.                            std::ifstream inFile;                            int                            numRows;                            //ask user input for file and open file                            //cout << "Name of language file to be read in: ";                            //cin >> fileName;                            inFile.open("french.txt");                            //inFile.open( fileName.c_str() );  // <--- Non needed from C++11 on.                            std::cout <<                            "File successfully processed!"                            <<                            '\northward';                            //take Language info and number of entries from top of .txt file                            inFile >> language >> numRows;     inFile.ignore(std::numeric_limits<std::streamsize>::max(),                            '\north');                            // <--- Requires header file <limits>. Added.                            //create a 2nd array for the languages in size of number of entries                            std::string 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 + 1 << ". " << french << " " << english << '\n';                            //        }                                                        //}                            for                            (int                            i = 0, j = 0; i < numRows && std::getline(inFile, french,                            ',') && std::getline(inFile, english language); i++, j = 0)     {         langArray[i][j++] = french;          langArray[i][j] = english language;          std::cout << i + one <<                            ". "                            << french <<                            " "                            << english <<                            '\n';     }      std::cout <<                            "\n\n  For checking array contents.\due north";                            for                            (int                            row = 0; row < 4; row++)     {           std::cout << row + 1 <<                            ". ";                            for                            (int                            col = 0; col < 2; col++)         {             std::cout << langArray[row][col] <<                            "  ";         }          std::cout <<                            '\n';     }                            // <--- Keeps console window open when running in debug mode on Visual Studio. Or a good fashion to pause the programme.                            // The next line may not be needed. If you take to press enter to see the prompt it is not needed.                            //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.                            std::cout <<                            "\n\northward Printing Enter to continue: "; 	std::cin.become();                            return                            0;                            // <--- Not required, merely makes a good interruption point.                            }                        

The for loop was a adept kickoff, simply you lot are over complicating the whole. The code higher up tin be washed in 1 for loop although it is different from a normal for loop.

The if argument is not needed considering the reads are done in the for condition and therefor the loop will end when (eof) is set.

In that location are two different for loops and either will work. I left them both so you tin see the difference.

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

Andy

Edit:

This produces the output of:

                                      File successfully processed!  // <--- I think you mean opened. If not information technology is in the wrong place.  one. bonjour hello ii. oui aye 3. non no four. merci thanks     For checking assortment contents. one. bonjour  how-do-you-do 2. oui  yes iii. not  no 4. merci  cheers    Press Enter to continue:                                  

Concluding edited on

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

                          1
2
3
4
5
vi
7
viii
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
xxx
31
32
33
34
35
36
37
38
39
forty
41
42
43
44
45
46
47
48
49
50
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
76
                                                      #include <iostream>                            #include <vector>                            #include <fstream>                            #include <string>                            struct                            Translation {     std::string to_translate;     std::string translated; };                            int                            main() {     std::string fileName, language, line;                            int                            num;      std::ifstream inFile("french.txt");                            if(!inFile)     {         std::cerr <<                            "Error opening input file.\n";                            return                            1;     }                            //take Language info and number of entries from top of .txt file                            inFile >> language >> num;                            /*********************************************************************     {         // Using an array, non 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 commencement word from the file.                            while(getline(inFile, translation[i].to_translate,                            ','))         {                            // Read the second word from the file.                            getline(inFile, translation[i].translated);             ++i;         }     }                            /***********************************************************************     {         // Or using dynamic array of two strings.         std::string(*array)[2] = new std::string[num][2];         size_t i = 0;          // Get the first give-and-take 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 not standard C++ - although some non-conforming compilers permit it. For standard C++, the size of the assortment has to be known at compile fourth dimension. If the size is only known at run-time (such equally here when reading a file), and so using a vector instead is the way to go.

                          i
two
3
iv
5
half-dozen
seven
viii
9
10
xi
12
xiii
fourteen
15
16
17
18
19
20
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;  	Translate(const                            std::string& f, std::string& e) : french(f), english(e) {} };                            int                            principal() { 	std::ifstream inFile ("french.txt");                            if                            (!inFile.is_open()) { 		std::cout <<                            "File cannot be opened!\n";                            return                            i; 	}                            int                            num;  	inFile >> num; 	inFile.ignore(std::numeric_limits<std::streamsize>::max(),                            '\n');  	std::vector<Interpret> words; 	words.reserve(num);                            for                            (std::string french, english; std::getline(inFile, french,                            ',') && std::getline(inFile, english language); words.emplace_back(french, english));                            for                            (const                            auto& w : words) 		std::cout << w.french <<                            '\t'                            << w.english <<                            '\due north'; }                        

Yet, as the aim is to create a translator then at some point y'all'll need to wait upwards a French give-and-take to convert to English language. The easiest style to facilitate a await-up like this is to apply a std::map. Consider:

                          1
2
3
4
5
6
7
8
9
10
11
12
xiii
fourteen
fifteen
16
17
18
19
xx
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                            primary() { 	std::ifstream inFile ("french.txt");                            if                            (!inFile.is_open()) { 		std::cout <<                            "File cannot be opened!\due north";                            return                            1; 	}                            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); words[french] = english);                            for                            (const                            motorcar& w : words) 		std::cout << w.commencement <<                            '\t'                            << w.second <<                            '\due north';  	std::cout <<                            "\noui is ";                            const                            automobile                            w {words.detect("oui")};                            if                            (w != words.end()) 		std::cout << w->second <<                            '\n';                            else                            std::cout <<                            "<non establish>\northward"; }                        

Topic archived. No new replies immune.

pattersonitth1992.blogspot.com

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

0 Response to "C++ Read String in File Into 2d Array"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel