I have a case where I am not allowed to use the string class so I am using a char array. Does anyone have any idea why I am getting all the junk characters after my char array when i print? The input file is a 2 line file containing (no quotes) "test 1" on the first line and "test 2" on the second line.
On a related note, how can you remove chars (or remove all the contents to have the array ready for the next iteration) from a char array while maintaining the same size [80] ? I don't think the code:
str1[0] = '\0';
is doing the trick - based on my testing of multi-line input files.
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <fstream>
using namespace std;
int main ()
{
int i, k, a, b, s, t, z, temp;
char str1[81];
char str2[81];
char comp1[81];
char comp2[81];;
ifstream infile;
infile.open("data.txt");
assert(infile);
while (infile) {
if (infile.peek() == EOF)
break;
infile.getline(str1,80);
infile.getline(str2,80);
cout << "length of string 1 is : " << strlen(str1) << endl;
cout << "length of string 2 is : " << strlen(str2) << endl;
cout << str1 << endl;
cout << str2 << endl << endl;
s = 0;
// Remove spaces and tabs
// moving to a new char array
for (int i=0 ; i<strlen(str1) ; i++) {
if (str1[i] != ' ' && str1[i] != '\t') {
cout << "S equals: " << s << "I equals: " << i << endl;
comp1[s] = str1[i];
cout << "added a letter to comp1, incrementing S, comp1 = " << comp1 << endl;
s++;
}
}
t = 0;
for (int k=0 ; k<strlen(str2) ; k++) {
if (str2[k] != ' ' && str2[k] != '\t') {
comp2[t] = str2[k];
cout << "added a letter to comp2, incrementing T, comp2 = " << comp2 << endl;
t++;
cout << "T equals: " << t << "K equals: " << k << endl;
}
}
cout << "comp1 length is: " << strlen(comp1) << endl;
cout << "comp2 length is: " << strlen(comp2) << endl;
cout << "comp1 is: " << comp1 << endl;
cout << "comp2 is: " << comp2 << endl;
str1[0] = '\0';
str1[0] = '\0';
comp1[0] = '\0';
comp2[0] = '\0';
}
return 0;
}
OUTPUT:
length of string 1 is : 6
length of string 2 is : 6
test 1
test 2
S equals: 0I equals: 0
added a letter to comp1, incrementing S, comp1 = t¸Ô
S equals: 1I equals: 1
added a letter to comp1, incrementing S, comp1 = teÔ
S equals: 2I equals: 2
added a letter to comp1, incrementing S, comp1 = tes
S equals: 3I equals: 3
added a letter to comp1, incrementing S, comp1 = testÿÿÿÿB÷¿è«Ì
S equals: 4I equals: 5
added a letter to comp1, incrementing S, comp1 = test1ÿÿÿB÷¿è«Ì
added a letter to comp2, incrementing T, comp2 = taÔ
T equals: 1K equals: 0
added a letter to comp2, incrementing T, comp2 = teÔ
T equals: 2K equals: 1
added a letter to comp2, incrementing T, comp2 = teÔ
T equals: 3K equals: 2
added a letter to comp2, incrementing T, comp2 = tesÔ
T equals: 4K equals: 3
added a letter to comp2, incrementing T, comp2 = testÔ
T equals: 5K equals: 5
comp1 length is: 15
comp2 length is: 11
comp1 is: test1ÿÿÿB÷¿è«Ì"
comp2 is: testÔ"