Reputation: 49
#include <iostream>
using namespace std;
int main()
{
int n,t=0,k=0;
cin>>n;
char data[n][100];
int num[n];
for(int i=0;i<n;i++)
{
while(1)
{
cin>>data[i][t];
cout<<data[i][t]<<endl;
if(data[i][t]=='\n') break;
k++;
if(k%2==1) t++;
}
cout<<i;
num[i]=(t-2)/2;
k=0;
t=0;
}
for(int i=0;i<n;i++)
{
while(1)
{
cout<<data[i][t];
if(t==num[i]) break;
t++;
}
t=0;
}
}
here is the code I have written in c++ which gives the even numbered characters from the starting half of every word given by the user but when giving input after pressing enter the loop should break but the loop is not breaking
while(1)
{
cin>>data[i][t];
cout<<data[i][t]<<endl;
if(data[i][t]=='\n') break;
k++;
if(k%2==1) t++;
}
Upvotes: 5
Views: 2798
Reputation: 12779
There are some ways to implement in C++ what OP is trying to do. I'd start avoiding Variable Length Arrays, which aren't in the Standard and using std::string
s and std::vector
s instead.
One option is to read an entire line from input with std::getline
and then process the resulting string to keep only the first half of even chars:
#include <iostream>
#include <string>
#include <vector>
int main() {
using std::cin;
using std::cout;
using std::string;
cout << "How many lines?\n";
int n;
cin >> n;
std::vector<string> half_words;
string line;
while ( n > 0 && std::getline(cin, line) ) {
if ( line.empty() ) // skip empty lines and trailing newlines
continue;
string word;
auto length = line.length() / 2;
for ( string::size_type i = 1; i < length; i += 2 ) {
word += line[i];
}
half_words.push_back(word);
--n;
}
cout << "\nShrinked words:\n\n";
for ( const auto &s : half_words ) {
cout << s << '\n';
}
return 0;
}
Another is, as Joachim Pileborg did in his answer, to disable skipping of leading whitespaces by the formatted input functions with std::noskipws
manipolator and then read a char at a time:
// ...
// disables skipping of whitespace and then consume the trailing newline
char odd, even;
cin >> std::noskipws >> odd;
std::vector<string> half_words;
while ( n > 0 ) {
string word;
// read every character in a row till a newline, but store in a string
// only the even ones
while ( cin >> odd && odd != '\n'
&& cin >> even && even != '\n' ) {
word += even;
}
// add the shrinked line to the vector of strings
auto half = word.length() / 2;
half_words.emplace_back(word.begin(), word.begin() + half);
--n;
}
// ...
Upvotes: 0
Reputation: 409364
By default formatted input using the "input" operators >>
skip white-space, and newline is a white-space character. So what's happening is that the >>
operator simply waits for some non-white-space input to be entered.
To tell the input to not skip white-space you have to use the std::noskipws
manipulator:
cin>>noskipws>>data[i][t];
Upvotes: 9