#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int T;
cin >> T;
char input[1000];
for(int i=0;i<T;i++)
{
cin.getline(input,sizeof(input));
cout << input << "\n";
}
return 0;
}
I am currently having problem getting string input using getline but it seems to work only for short lines. Here is my input and output:
Input:
3 Can I have a large container of coffee right now Can I have a large container of tea right now Now I wish I could recollect pi Eureka cried the great inventor Christmas Pudding Christmas Pie Is the problems very center
Output:
Can I have a large container of coffee right now Can I have a large container of tea right now
It doesn't store last line why?
You can do it with this way, using string
instead of char []
:
int main() {
int T;
cin >> T;
string input;
for(int i=0;i<T;i++)
{
std::getline(std::cin,input);
cout << input << endl;
}
return 0;
}
Check the code with the following test :
Input :
3 Can I have a large container of coffee right now Can I have a large container of tea right now Now I wish I could recollect pi Eureka cried the great inventor Christmas Pudding Christmas Pie Is the problems very center
Output:
3 Can I have a large container of coffee right now Can I have a large container of tea right now Now I wish I could recollect pi Eureka cried the great inventor Christmas Pudding Christmas Pie Is the problems very center
Your problem is the first input operator:
cin >> T;
This reads a number and stores it as an integer in T, but leaves the newline in the stream. Now the loop will read three lines, but the first will be an empty line.
You can fix this in several ways, the simplest is to just discard the newline after fetching the number:
cin >> T;
cin.getline(input, sizeof input);
A better way will be to check for end of file instead of fetching the number of lines in advance. And use std::string
instead of char arrays as others have suggested.
Try something like this
while(cin.getline(input,sizeof(input))){
}
Try:
int main() {
int T;
cin >> T;
std::string temp;
std::string input;
for(int i=0;i<T;i++)
{
while(std::getline(std::cin,temp)) {
input += temp;
}
std::cout << input << endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.