Problems with string input using getline() - c++

Here is my solution to the problem in the codeforces http://codeforces.com/problemset/problem/499/B . I am facing problem in inputting the string. It termintes after line 10 (see code) before i give input str to it and output some weird chars.
Input: 4 3
codeforces codesecrof
contest round
letter message
Output:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
int N, M;
string str;
cin>>N>>M;
string A[M], B[M];
for(int i=0; i<M; i++)
cin>>A[i]>>B[i]; // line 10
getline(cin,str);
char res[N+1];
for(int i=0; i<M; i++){
int j= str.find(A[i]);
int k;
int x=0;
if(B[i].length() < A[i].length()){
for(k=j; k<B[i].length(); k++){
res[k]= B[i][x];
x++;
}
}else{
for(k=j; k<B[i].length(); k++){
res[k]= B[i][x];
x++;
}
}
res[k]=' ';
}
for(int i=0; i<=N; i++ )
cout<<res[i];
cout<<endl;
return 0;
}

There is a newline character left in the input stream after:
cin>>N>>M;
You need a line of code that will read and discard the rest of the line. Add a line;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
after that line.
Add
#include <limits>
to be able to use std::numeric_limits.

Related

Is there a way to read the numbers on consecutive specific lines in C++?

Let's assume I have a program which takes as an input a file
(numbers.in)
which contains on the first line a number n, on the second line n numbers separated using a space, and on the third line, some other n numbers separated by a space.
I do know how much n is, for I read it form the first line. I don not know how to jump on the second line and read ONLY the numbers on that line, then to thew third etc.
I want to save the numbers on the second line in a vector A in the same order they are on that line and in a vector B the numbers on the third line, as shown. So far I have this:
#include <stream>
#include <string>
using namespace std;
ifstream fin("numbers.in");
ofstream fout("result.out");
int main()
{ int N;
string line;
fin>>N;
long long A[N];
unsigned long long B[N];
for(int i=0; i<=N-1; i++)
{
while (!fin.eof())
{
A[i]=getline(fin, );
}
}
for(int i=0; i<=N-1; i++)
{
while (!fin.eof())
{
B[i]=getline(fin, );
}
}
How do I do that?
By writing code to do so.
#include <fstream>
#include <vector>
std::ifstream fin("numbers.in");
std::ofstream fout("result.out");
int main()
{
int N;
// read the number of numbers
fin>>N;
// allocate vectors for storing numbers
std::vector<long long> A(N);
std::vector<unsigned long long> B(N);
// read N numbers
for(int i=0; i<=N-1; i++)
{
fin>>A[i];
}
// read another N numbers
for(int i=0; i<=N-1; i++)
{
fin>>B[i];
}
}
The loop for(int i=0; i<=N-1; i++) is not bad, but for(int i=0; i<N; i++) is the common way, at least in my view.

Failing the test cases in printing the even-indexed and odd-indexed characters of strings

Task at hand:
Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line.
The test cases are written such that The first line contains an integer, N (the number of test cases). Each line i of the N subsequent lines contain a String.
LINK TO THE QUESTION : https://www.hackerrank.com/challenges/30-review-loop/problem
My code:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
void sum(string s1)
{
//getting size of string
int len;
len=s1.length();
//taking string values to an array
char arr[len];
for(int i=0;i<len;i++)
{
arr[i]=s1[i];
}
//displaying the items
for(int i=0;i<len;i++)
{
if(i%2==0)
std::cout<<(arr[i]);
}
std::cout<<" ";
for(int i=0;i<len;i++)
{
if(i%2!=0)
std::cout<<(arr[i]);
}
}
int main()
{
string s1;
std::cin>>s1;
sum(s1);
return 0;
}
Note:I think my code is correct , but I am failing the test cases.
This would be the correct main, if I understood the task correctly:
int main()
{
int count = 0;
cin >> count;
for(int i = 0; i < count; i++){
string s1;
cin>>s1;
sum(s1);
}
return 0;
}
You should first take input for number of cases, Then run a loop till that number of cases, Call your function in that loop
int cases;
cin >> cases;
for (i = 0 to cases-1) {
//your code in main here
}

Not getting the output I want

I am trying to write a c++ program to read a txt file containing data (122X300 matrix - tab delimited matrix) into my code and get it to display. The following is the code I wrote after referring extensively to google and many similar questions on this site. On running the code, I do not get any errors, however it does give me huge list of numbers which I cant seem to make any sense of. The following is the code: Any help would be great. I do not know where I am going wrong. Thanks.
DID some changes after considering the comment below by #ZekeMarsh, the problem now is that my text data is like:
Data Matrix Snapshot
The output I am getting is this:
Output of Code
The row counter does not move over to the next row,instead continues in the same row after incrementation....No idea why. The code modified is as follows:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int main(){
int HEIGHT = 3;
int WIDTH = 2;
int array_req[HEIGHT][WIDTH];
string userinputprompt, filename;
userinputprompt = "Data Filename: ";
cout<<userinputprompt<<endl;
getline(cin,filename);
ifstream inputfile;
inputfile.open(filename.c_str());
for(int i=0; i<HEIGHT; i++)
{
for(int j=0; j<WIDTH; j++)
{
/*if(!(inputfile>>array_req[i][j]))
{
cerr<<"Error";
break;
}
else if(!inputfile) // its error.. , can use a cerr here...
{
cerr<<"Error";
break;
}
else*/
inputfile>>array_req[i][j];
cout<<i<<","<<j<<"-->"<<array_req[i][j]<<endl;
}
/* This is not needed, read above comment
else
{
inputfile >> array_req[i][j];
}*/
}
for(int p=0; p<HEIGHT; p++)
{
for(int q=0; q<WIDTH; q++)
{
cout<<array_req[p][q]<<" ";
}
cout<<"\n";
}
inputfile.close();
getchar();
return 0;
}
.
EDITED CODE - The output array is a null matrix. Please help. What is wrong in the code ..compiles correctly. Trying to read line by line using getline and stringstream based on a lot of examples I read here..still not working.
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>
const int HEIGHT = 3;
const int WIDTH = 4;
const int BUFFSIZE = 10000;
using namespace std;
int main(){
int array_req [HEIGHT][WIDTH];
char buff[BUFFSIZE];
string userinputprompt, filename;
userinputprompt = "COLORDATA FILENAME: ";
cout<<userinputprompt<<endl;
getline(cin,filename);
ifstream inputfile;
stringstream ss;
inputfile.open(filename.c_str());
for (int i=0; i<HEIGHT; i++)
{
inputfile.getline(buff,BUFFSIZE,'\n');
ss<<buff;
for(int j=0;j<WIDTH; j++)
{
ss.getline(buff,1000,'\n');
array_req[i][j]=atoi(buff);
}
ss<<"";
ss.clear();
}
for(int p=0; p<HEIGHT; p++)
{
for(int q=0; q<WIDTH; q++)
{
cout<<array_req[p][q]<<" ";
}
cout<<"\n";
}
inputfile.close();
getchar();
return 0;
}
First of all during the printing of your array, you are not delimiting your data with anything which will result in a line of numbers. You should add delimiter and line breaks.
Second and most importantly: you try printing the full value of the array while it has not been filled up yet. I believe you meant to put the printing outside of the loop that works with your variable i . Now you are printing garbage in the places where the array was not filled yet.
Edit: Here is only the reading part as I believe that is only what you are looking for:
for (int i = 0; i < HEIGHT; ++i)
{
std::string tmpString;
std::getline(inputfile, tmpString);
std::stringstream ss(tmpString);
for(int j=0;j < WIDTH; ++j)
{
ss >> array_req[i][j];
}
}

Can't get last int from .txt file

My Issue involves reading integers from a text file, saving them to an array and then copying the array to a new .txt file.
So there is a file "krol.txt"
2 4
3 7
3 13
2 4
3 1
The problem is that it never ever save the last '1' from the input .txt file. I have no idea why. I think its about EOF on last character in file but why it works like that? Can anyone help me?
This is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
ofstream outFile;
ifstream fin;
fin.open("krol.txt");
int l=0;
char ch;
while (fin.good()) {
fin.get(ch);
if(ch=='\n') l++;
}
fin.close();
fin.open("krol.txt");
int temp[l][2];
int savel=l;
l=0;
int i=0;
while (fin >> (temp[l][i])) {
i++;
if(i==2) {
i=0;
l++;
}
}
outFile.open("save.txt");
for (int i=0, j=0;j<savel;i++) {
if (i==2) {
i=0; j++;
}
outFile << temp[j][i];
}
outFile.close();
system("PAUSE");
return 0;
}
This saves all the numbers just fine. The problem is, it stores additional numbers in save.txt.
With
while (fin.good()){
...
}
you count the last line twice. This gives you two additional uninitialized ints. These two ints can show up as any integer.
I see two problems. Your first loop to get the number of lines should be more like
while (fin.get(ch)){
if (ch == '\n')
l++;
}
If the last line doesn't have a final \n, you could end with one line less than you need.
And the output loop could be simplified to
for (int j = 0; j < savel; j++){
for (int i = 0; i < 2; i++)
outFile << temp[j][i] << ' ';
}
And finally, if you use c++, you should consider using std::vector instead of plain arrays. Then you don't need to preallocate your array and can read the file in just one pass.
There might be 4 '\n' chars in that file have you considered that?

Polymorphic addition in C++

I am trying to create a program that adds a polymorphic number that are organized in Rows and columns, so hopefully if you take a look at the arrays I have created you will get an idea of what I am trying to do, but think of it as this way you have 3 arrays A, B, C and I am trying to calculate A+B=C.
But I don't get anything but foolishness, I need help because I know so little about data structures:
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int i,j,A[10][10],B[10][10],C[10][10], nf, nc;
cout<<"#Rows: "<<endl;
cin>>nf;
cout<<"#Columns: "<<endl;
cin>>nc;
//For the A part
for(int i=0; i<=nf;i++){
cout<<"Enter the row Number # "<<i;
for(int j= 0; j<=nc;j++){
cout<<"Enter Column Column#"<<j<<endl;;
cin>>A[i][j];
}}
//For the B part
for(int i=0; i<=nf;i++){
cout<<"Enter Row # "<<i<<endl;
for(int j= 0; j<=nc;j++){
cout<<"Enter Column# "<<j<<endl;
cin>>B[i][j];
}}
//Calculation
for(int i=0; i<nf;i++)
for(int j=0;j<nc;j++)
C[i][j]= A[i][j]+ B[i][j];
//output
for(int i=0; i<nf;i++)
for(int j=0;j<nc;j++)
cout<<C[i][j];
system("PAUSE");
return EXIT_SUCCESS;
}
the bounds in you'r input for loops i guess is not what you want it to be or atleast it is not consistent with the calculation loop
for(int j= 0; j<=nc;j++) vs for(int j= 0; j<nc;j++)
You have to initialize your cells to 0. else they will contain junk value and that will be used for addition. You can do it by initialization or using a loop.
int main()
{
int nf, nc, A[10][10]={0}, B[10][10]={0}, C[10][10]={0};
}
You have unused variables i and j. they are not a reason for erroneous output but still avoid it.
you can find a simplified corrected form of your program here (Array Bounds have also been corrected)
for(int i=0; i<nf;i++)
for(int j= 0; j<nc;j++)
these loops are used in both input and output
I hope it will be your response:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i,j,A[10][10],B[10][10],C[10][10], nr, nc;
cout<<"#Rows: "<<endl;
cin>>nr;
cout<<"#Columns: "<<endl;
cin>>nc;
//For the A part
for(int i=0; i<nr;i++){
for(int j= 0; j<nc;j++){
cout<<"Enter the A["<<i<<"]["<<j<<"]"<<endl;
cin>>A[i][j];
}
}
//For the B part
for(int i=0; i<nr;i++){
for(int j= 0; j<nc;j++){
cout<<"Enter the B["<<i<<"]["<<j<<"]"<<endl;
cin>>B[i][j];
}
}
//Calculation
for(int i=0; i<nr;i++)
for(int j=0;j<nc;j++)
C[i][j]= A[i][j]+ B[i][j];
//output
for(int i=0; i<nr;i++)
for(int j=0;j<nc;j++)
cout<<C[i][j];
system("PAUSE");
return EXIT_SUCCESS;
}
Dont complicate things with many cout statements.
cout<<"Enter a["<<i<<"]"<<"["<<j<<"] : ";
cin>>a[i][j];
i = 0 to nf means you are reading nf+1 elements. So there is array out of bound. Be careful with i<nf and i<=nf.