I wrote this function to read a char array from cin:
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include "main.h"
int read (char* buffer, int size) {
//read from standart input (with whitespaces)
//cin >> buffer;
cin.get(buffer, size);
cin.ignore(1, '\n');
cout << "cin get buffer: " << buffer << endl;
//if not a correct input
if (!cin.good())
return 0;
cout << "cin.good: " << cin.good() << endl;
//user wants to quit
if (!strcmp (buffer, "end"))
return 0;
return 1;
}
When I call this function for the first time in my main returncode = read (first, MAX)
and enter blabla
, it reads "blabla" into the buffer. (I checked via cout-for-loop)
When I want to read another array (for comparison), and do the exact same thing returncode = read(second, MAX)
, it only reads " labla" where second[0]
remains empty.
Where is my fault? Feel free to ask for the rest of the code, but I think the fault is within this code snippet.
Thank you in advance!
ps: I am really new to c++, so please be patient with me :) pps: This is a university test, we are not allowed to use the string class..
EDIT: A simple main to test the above
main.cpp:
#include <iostream>
#include "main.h"
#define MAX 200
using namespace std;
int main () {
char first [MAX] = {0};
char second [MAX] = {0};
cout<<"Please enter the first string to compare: "<<endl;
returncode = read (first, MAX);
cout<<"Please enter the second string to compare: "<<endl;
returncode = read (second, MAX);
switch (strcmp_ign_ws(first, second, MAX)) {
case EQUAL:
cout << "Strings are equal!" << endl;
break;
case SMALLER:
cout << "String 1 is lexically smaller!" << endl;
break;
case BIGGER:
cout << "String 1 ist lexically bigger!" << endl;
break;
}
}
and the main.h:
#define EQUAL 0
#define SMALLER -1
#define BIGGER 1
int read (char*, int);
int strcmp_ign_ws (char*, char*, int);
int main ();
EDIT 2: adding the String compare ignore whitespace function
As the error does not seem to be in the read function, this is the file using the two inputed-buffers first and second:
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <ctype.h>
#include "main.h"
using namespace std;
char * rm_ws (char * buffer, const int size) {
int i,j;
char *output=buffer;
for (i = 0, j = 0; i<size; i++,j++)
{
if (buffer[i]!=' ')
output[j]=buffer[i];
else
j--;
}
output[j]=0;
return output;
}
int strcmp_ign_ws (char * first, char * second, int size) {
first = rm_ws(first, size);
second = rm_ws(second, size);
if (strcmp (first, second) == 0)
return EQUAL;
if (strcmp (first, second) < 0)
return SMALLER;
if (strcmp (first, second) > 0)
return BIGGER;
}
}
ps: the rm_ws
function is from stackoverflow already