C++ .txt to array

From C++ to PHP, debugging to webhosting; help and discussion about writing your latest program to running your website. NOT for help when your PC won't work.

Announcements Posted on
Please change your TSR password 23-05-2013
Sign in to Reply
  1. AaronT's Avatar
    • Full Member
    C++ .txt to array
    So I've got a list of numbers, eg:

    012345678
    123456789
    234567890
    345678901
    456789012
    567890123
    678901234
    789012345
    890123456


    I want to put each number of each line into a 2D array. So the first line,012345678, becomes
    array[0][0] = 0, array[0][1] =1, array[0][2] = 2 etc.

    How on earth do i do this in C++?!

    The numbers will be coming from a .txt file with arbitrary name. I think what i'm asking is how do you open the txt file and pull the numbers out one by one.
  2. Psyk's Avatar
    • TSR Royalty
    • Location: Leamington Spa
    • Posts: 19,081
    Re: C++ .txt to array
    So will all the numbers be single digits?

    You can use an ifstream, and then read a single "char" in at a time (using the >> operator). This will give you the ascii value of the character, which can quite easily be converted to the actual number it represents. You just take away the ascii value of the character '0' from the value you read in. You'll probably want to check it actually is a digit character first though.
  3. AaronT's Avatar
    • Full Member
    Re: C++ .txt to array
    (Original post by Psyk)
    So will all the numbers be single digits?
    They will.

    I'll have a stab at getting ifstream to print the numbers onto the console without just using a print function, then it should be easy peasy right?
  4. AaronT's Avatar
    • Full Member
    Re: C++ .txt to array
    Code:
    //add values to temp array
    while(!sudoku.eof())
    {
    	sudoku>>temp[count0];
    	count0 = count0 + 1;
    }
    This seems to work intially. However, outside of the loop, printing the values in temp[] doesn't seem to work...

    Heres the full code:

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int count0=0, count1=0, count2=0;
    
    const int file_name_length = 20;
    char in_file[file_name_length];
    
    void open_txt()
    {
    	cout<<"Please type the file name"<<endl<<endl;
    
    	cin>>in_file;
    	cout<<endl<<endl;	
    	
    	for (count0=19; count0>0; count0--)	//Counts backward to find last char
    	{																				
    		if ((in_file[count0]==0) && (in_file[count0-1]!=0))
    		{					
    			in_file[count0]='.';
    			in_file[count0+1]='t';
    			in_file[count0+2]='x';
    			in_file[count0+3]='t';
    		}
    	}
    }
    void read_txt()
    {
    	const int width = 8, height = 8;
    	char in_file_numbers[width][height], temp[80];
    
    	ifstream sudoku;
    	sudoku.open(in_file);
    
    	count0 = 0;
    
    	//add values to temp array
    	while(!sudoku.eof())
    	{
    		sudoku>>temp[count0];
    		count0 = count0 + 1;
    		cout<<temp[count0 - 1];
    	}
    
    	sudoku.close();
    
    	system("PAUSE");
    }
    void help_file()
    {
    
    }
    
    void main_menu()
    {
    	cout<<"Sudoku Solver beta v1.0"<<endl<<endl;
    
    	system("PAUSE");
    	system("CLS");
    
    	cout<<"Main Menu:"<<endl<<endl;
    	
    	cout<<"[1]	Sudoku Solver"<<endl;
    	cout<<"[2]	Help File"<<endl<<endl;
    
    	int main_choice;
    
    	cin>>main_choice;
    
    	system("CLS");
    
    	if(main_choice == 2)
    	{
    		help_file();
    	}
    }
    
    void main()
    {
    	main_menu();
    	open_txt();
    	read_txt();
    }
    Theres an error at the end of read_txt(). The temp[] array is corrupting, how do i rectify this?
  5. Psyk's Avatar
    • TSR Royalty
    • Location: Leamington Spa
    • Posts: 19,081
    Re: C++ .txt to array
    (Original post by AaronT)
    Code:
    //add values to temp array
    while(!sudoku.eof())
    {
    	sudoku>>temp[count0];
    	count0 = count0 + 1;
    }
    This seems to work intially. However, outside of the loop, printing the values in temp[] doesn't seem to work...

    Heres the full code:

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int count0=0, count1=0, count2=0;
    
    const int file_name_length = 20;
    char in_file[file_name_length];
    
    void open_txt()
    {
    	cout<<"Please type the file name"<<endl<<endl;
    
    	cin>>in_file;
    	cout<<endl<<endl;	
    	
    	for (count0=19; count0>0; count0--)	//Counts backward to find last char
    	{																				
    		if ((in_file[count0]==0) && (in_file[count0-1]!=0))
    		{					
    			in_file[count0]='.';
    			in_file[count0+1]='t';
    			in_file[count0+2]='x';
    			in_file[count0+3]='t';
    		}
    	}
    }
    void read_txt()
    {
    	const int width = 8, height = 8;
    	char in_file_numbers[width][height], temp[80];
    
    	ifstream sudoku;
    	sudoku.open(in_file);
    
    	count0 = 0;
    
    	//add values to temp array
    	while(!sudoku.eof())
    	{
    		sudoku>>temp[count0];
    		count0 = count0 + 1;
    		cout<<temp[count0 - 1];
    	}
    
    	sudoku.close();
    
    	system("PAUSE");
    }
    void help_file()
    {
    
    }
    
    void main_menu()
    {
    	cout<<"Sudoku Solver beta v1.0"<<endl<<endl;
    
    	system("PAUSE");
    	system("CLS");
    
    	cout<<"Main Menu:"<<endl<<endl;
    	
    	cout<<"[1]	Sudoku Solver"<<endl;
    	cout<<"[2]	Help File"<<endl<<endl;
    
    	int main_choice;
    
    	cin>>main_choice;
    
    	system("CLS");
    
    	if(main_choice == 2)
    	{
    		help_file();
    	}
    }
    
    void main()
    {
    	main_menu();
    	open_txt();
    	read_txt();
    }
    Theres an error at the end of read_txt(). The temp[] array is corrupting, how do i rectify this?
    When you say the temp[] array is corrupting, what do you mean? Does it print out seemingly random characters if you try and print the contents of the temp array?
  6. AaronT's Avatar
    • Full Member
    Re: C++ .txt to array
    (Original post by Psyk)
    When you say the temp[] array is corrupting, what do you mean? Does it print out seemingly random characters if you try and print the contents of the temp array?
    In visual studio, the debug won't let me run past read_txt because the temp[] array is corrupt. If i try to print the contents of temp[] outside of the loop i mentioned earlier, it prints a random heap of mess...
  7. TheUnbeliever's Avatar
    • TSR Demigod
    • Location: Scotland
    • Posts: 5,838
    Re: C++ .txt to array
    Last I checked, 9 squared was 81 not 80.

    EDIT: Also, you don't typically need to call std::ifstream::close. cf RAII
    Last edited by TheUnbeliever; 28-05-2012 at 00:34.
  8. TheUnbeliever's Avatar
    • TSR Demigod
    • Location: Scotland
    • Posts: 5,838
    Re: C++ .txt to array
    Also, alternative solution:

    Code:
    #include <iostream>
    #include <vector>
    #include <fstream>
    #include <iterator>
    #include <algorithm>
    #include <boost/lexical_cast.hpp>
    
    int main()
    {
    	std::ifstream ifs("C:\\Users\\Administrator\\Desktop\\data.txt");
    	std::istream_iterator<char> end, begin(ifs);
    
    	std::vector<int> digits;
    	std::for_each(begin, end, [&digits](char c) { digits.push_back(boost::lexical_cast<int>(c)); });
    }
    (lexical_cast is trivial to implement if you're averse to Boost. If you can't use C++11, virtually the same thing can be achieved with TR1's Bind. If you can't use any of these, you have my sympathy.)

    Still doesn't verify the file is appropriately formatted, but at least removes the overflow bug.
    Last edited by TheUnbeliever; 28-05-2012 at 00:31.
  9. Psyk's Avatar
    • TSR Royalty
    • Location: Leamington Spa
    • Posts: 19,081
    Re: C++ .txt to array
    (Original post by AaronT)
    In visual studio, the debug won't let me run past read_txt because the temp[] array is corrupt. If i try to print the contents of temp[] outside of the loop i mentioned earlier, it prints a random heap of mess...
    The temp array is declared inside the read_txt function, so it won't be available outside of that function. Outside of the loop should be fine, but you can't use it outside of the function.

    Also as The Unbeliever said, your array might not be big enough. You don't have any checks in there to stop overflowing it. You should stop reading after 81 characters, or however many you expect to be there. It will also read in the new line characters so you might want to watch out for that too.
  10. AaronT's Avatar
    • Full Member
    Re: C++ .txt to array
    (Original post by TheUnbeliever)
    Also, alternative solution:

    Code:
    #include <iostream>
    #include <vector>
    #include <fstream>
    #include <iterator>
    #include <algorithm>
    #include <boost/lexical_cast.hpp>
    
    int main()
    {
    	std::ifstream ifs("C:\\Users\\Administrator\\Desktop\\data.txt");
    	std::istream_iterator<char> end, begin(ifs);
    
    	std::vector<int> digits;
    	std::for_each(begin, end, [&digits](char c) { digits.push_back(boost::lexical_cast<int>(c)); });
    }
    (lexical_cast is trivial to implement if you're averse to Boost. If you can't use C++11, virtually the same thing can be achieved with TR1's Bind. If you can't use any of these, you have my sympathy.)

    Still doesn't verify the file is appropriately formatted, but at least removes the overflow bug.
    Thanks for the useful code, i'll implement it straight into the source. Also, I've been taught very little C++, and from what I've been told, we were taught in an odd style, so trying to teach myself stuff like this quickly becomes very difficult!

    (Original post by TheUnbeliever)
    Last I checked, 9 squared was 81 not 80.

    EDIT: Also, you don't typically need to call std::ifstream::close. cf RAII
    I was taught that arrays have n+1 amount of 'spaces' where array[n]. So if an array had 9 spaces, n=8, and therefore another array that has 9 times the amount of spaces, n=(9*9)-1=80...
  11. AaronT's Avatar
    • Full Member
    Re: C++ .txt to array
    (Original post by Psyk)
    Also as The Unbeliever said, your array might not be big enough. You don't have any checks in there to stop overflowing it. You should stop reading after 81 characters, or however many you expect to be there. It will also read in the new line characters so you might want to watch out for that too.
    Made the arrays bigger. Works now!
  12. TheUnbeliever's Avatar
    • TSR Demigod
    • Location: Scotland
    • Posts: 5,838
    Re: C++ .txt to array
    (Original post by AaronT)
    I was taught that arrays have n+1 amount of 'spaces' where array[n]. So if an array had 9 spaces, n=8, and therefore another array that has 9 times the amount of spaces, n=(9*9)-1=80...
    Yeah, that's just wrong, sorry. array[n] has n elements, indexed from 0 to n-1.

    What may have caused the confusion is what happens when you initialize a char[] using a string literal:

    char sz[] = "A"; // sz has 2 elements - {'A', '\0'}

    This isn't really a special case, although it's often taught as though it were. String literals just happen to carry an implicit null terminator.
  13. AaronT's Avatar
    • Full Member
    Re: C++ .txt to array
    (Original post by TheUnbeliever)
    Yeah, that's just wrong, sorry. array[n] has n elements, indexed from 0 to n-1.

    What may have caused the confusion is what happens when you initialize a char[] using a string literal:

    char sz[] = "A"; // sz has 2 elements - {'A', '\0'}

    This isn't really a special case, although it's often taught as though it were. String literals just happen to carry an implicit null terminator.
    ^^Probably why not a lot of people did very well in our first c++ assignment in 1st semester!
Sign in to Reply
Share this discussion:  
Useful resources
Article updates
Moderators

We have a brilliant team of more than 60 volunteers looking after discussions on The Student Room, helping to make it a fun, safe and useful place to hang out.

Reputation gems:
The Reputation gems seen here indicate how well reputed the user is, red gem indicate negative reputation and green indicates a good rep.
Post rating score:
These scores show if a post has been positively or negatively rated by our members.