I'm trying to move one big C++ string (with separators) like one below

& 12345 & 12345 & 23423 & 90323 &

into 3x5 array like one below with the first group of numbers excluded

char array[3][5];

{ '1' , '2' , '3' , '4' , '5'} ,
{ '2' , '3' , '4' , '2' , '3'},
{'9' , '0' , '3' , '2' , '3'};

I thought I've got it at first but after trying to display the output
it simply failed to display the value correctly. Pardon me if this has been asked before. I'm just looking for the most efficient way to this.

Cheers

Recommended Answers

Yeah. Some the copying should be done a bit different from what you have. Some ideas:
[code]#include

include

using namespace std;

int main()
{
int count, i, j = 0, k = 0;
string str = "& 12345 & 12345 & 23423 & 90323 &";
char array[3][5] …

Jump to Post

All 6 Replies

Re: C++ string to 2-D char array 80 80

Say, why not show us the code?

Re: C++ string to 2-D char array 80 80
int count;
	
	int k = 0;
	int j = 0;
	string str = "& 12345 & 12345 & 23423 & 90323 &";
	char array[3][5];
	
	for(int i = 0; count < 5 ; i++){
		if(str[i] == '&')count++;
		
		if(count >= 2 ){  /* start copying only after two ampersand */
			
			if(str[i] != '&')array[j][k] = str[i];
			
			k++;
			
			if(str[i] == '&') j++;					
		}	
	}

I think this code is pretty messed up. That's why it's not working.

Re: C++ string to 2-D char array 80 80

I don't see where you're trying to display it. Can you post the code?

Re: C++ string to 2-D char array 80 80
for(int m = 0; m < 3; m++){
		for(int n = 0; n < 5 ; n++){
			cout << array[m][n] << " " ;
		}
		cout << endl;
	}

output should be something like this

1 2 3 4 5
9 0 5 6 2
1 2 4 4 5

but some random characters show up.

Re: C++ string to 2-D char array 80 80

Yeah. Some the copying should be done a bit different from what you have. Some ideas:

#include <iostream>
#include <string>
using namespace std;

int main()
{
   int count, i, j = 0, k = 0;
   string str = "& 12345 & 12345 & 23423 & 90323 &";
   char array[3][5] = {0};

   for ( i = 0; str[i]; ++i )
   {
      if ( str[i] == '&' )
      {
         count++;
      }
      else if ( str[i] == ' ' )
      {
         // skip
      }
      else
      {
         if ( count >= 2 )
         {
            array[j][k] = str[i];
            if ( ++k > 5 )
            {
               k = 0;
               if ( ++j > 3 )
               {
                  break;
               }
            }
         }
      }
   }
   for ( j = 0; j < 3; ++j )
   {
      for ( k = 0; k < 5; ++k )
      {
         cout << array[j][k] << ' ';
      }
      cout << "\n";
   }
   return 0;
}

/* my output
1 2 3 4 5 
2 3 4 5 2 
4 2 3 9 0 
*/
Re: C++ string to 2-D char array 80 80

Thank you very much for showing me how it should be done

Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.