C ++ reads every 3 elements in an array

I am working on a project and I want to print for each 3 elements of a string array. Therefore, if the string is "cadgfacbda", I want it printed on the console:

** "cad gfa cbd a" **

This is the code:

string str("cadgfacbda"); for(int i = 0 ; i < 3 ; i++) { for(int j = i ; j < str.size() ; j +=3 ) { cout << str[j]<<" "; } cout<<endl; } 

But I get:

cgca

afb

dad

+5
source share
7 answers

Code in only one loop:

 string str("cadgfacbda"); for(int i = 0 ; i < str.size() ; i++) { if(i && i%3==0) cout<<" "; cout << str[i]; } cout<<endl; 
+6
source

I think this should happen something like this:

  string str("cadgfacbda"); for(int i = 0 ; i < str.size() ; i++) { cout << str[j]<<" "; if( i % 3 == 0 ) cout<<endl; } 

This of course assumes that you will need a new line after every three elements. If you just need spaces, you can try this instead:

  string str("cadgfacbda"); for(int i = 0 ; i < str.size() ; i++) { cout << str[j]; if( i % 3 == 0 ) cout<<" "; } 
+4
source
 int main() { typedef std::string::size_type size_type; std::string str("cadgfacbda"); const size_type STEP_SIZE = 3; for(size_type i = 0 ; i < str.size() ; i+=STEP_SIZE) { std::cout << str.substr(i, STEP_SIZE) << " "; } std::cout << std::endl; return 0; } 
+3
source

This should work:

  string str("cadgfacbda"); for(int i = 0 ; i < str.size() ; i++) { if(i % 3 == 0 && i != 0) cout << " "; cout << str[i]; } cout << endl; 
+2
source
 #include<stdio.h> #include<string.h> #include<string> int main() { string str("cadgfacbda"); char arr[]=str.to_char(); for(int i=1;i<=strlen(arr);i++) { printf("%c",arr[i-1]); if(i%3==0) { printf(" "); } } } 
+2
source

This should work too:

 int main() { std::string str = "cadgfacbda"; for (int i = 0; i < str.length()-3; i++) { for (int j = 0; j < 3; ++j) { if ((3 * i + j) < str.length()) std::cout << str[3 * i + j]; } std::cout << " "; } return 0; } 
+2
source

I'm a little late, but you can just fine-tune.

 std::string str("cadgfacbda"); for (std::size_t i = 0; i < str.size(); i += 3) { std::cout << str.substr(i, 3) << " "; } 

This saves you a ton of code and is more readable.

Living example

+2
source

Source: https://habr.com/ru/post/1244730/


All Articles