IN C++ Write a program in c++ that will read from a file the following sentence:
ID: 3847818 • Letter: I
Question
IN C++
Write a program in c++ that will read from a file the following sentence:
The quick brown fox jumps over the lazy dog
Each word must be read into one location in an array beginning with the first element. You must declare an array as follows:
char *words [9] ; // this is an array of c- strings.
HINT
words[0] will contain "the"
words[1] will contain "quick"
write a function int length (const char *a) to determine the length of each string by incrementing the pointer until we find the null character ''. Once you have determined hte length of each string, fill the following arrays as follow:
char *t3[[ ] = {"the", ...
char *t4 [ ] = {"quick", "brown", ...
where a each number is the length of the string ( not counting the null character). continue adding each string to its respective array ( t3, t4, ...) until you have reached the end of the array called words.Do not use 2dimensional arrays.
Finally, print all words of each arrayvertically seperated by a blank line
The
T
h
e
Quick
q
u
i
c
k
ect....
Explanation / Answer
c++ code:
#include <bits/stdc++.h>
using namespace std;
int lenght(char* tmp)
{
int j = 0;
while(tmp[j] != '')
{
j++;
}
return j;
}
int main()
{
string filename = "sentence.txt";
// cout << "Enter the filename!" << endl;
// cin >> filename;
char* words[9];
int n = 0;
string line;
ifstream myfile (filename.c_str());
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
vector< string > tokens; // Create vector to hold our words
while (ss >> buf)
{
tokens.push_back(buf);
char* s = new char[buf.size() + 1];
copy(buf.begin(), buf.end(), s);
s[buf.size()] = '';
words[n] = s;
n++;
}
int n1 = 0; int n2 = 0; int n3 = 0;
char *t3[10];
char *t4[10];
char *t5[10];
for (int i = 0; i < tokens.size(); ++i)
{
char* tmp = words[i];
int len = lenght(tmp);
if(len == 3)
{
t3[n1] = tmp;
n1++;
}
if(len == 4)
{
t4[n2] = tmp;
n2++;
}
if(len == 5)
{
t5[n3] = tmp;
n3++;
}
}
for (int i = 0; i < n1; ++i)
{
char* tmp = t3[i];
cout << tmp << endl;
int j = 0;
while(tmp[j] != '')
{
cout << tmp[j] << endl;
j++;
}
}
for (int i = 0; i < n2; ++i)
{
char* tmp = t4[i];
cout << tmp << endl;
int j = 0;
while(tmp[j] != '')
{
cout << tmp[j] << endl;
j++;
}
}
for (int i = 0; i < n3; ++i)
{
char* tmp = t5[i];
cout << tmp<< endl;
int j = 0;
while(tmp[j] != '')
{
cout << tmp[j] << endl;
j++;
}
}
}
myfile.close();
}
else
{
cout << "Unable to open file" << endl;
exit(1);
}
return 0;
}
Sentence.txt
The quick brown fox jumps over the lazy dog
Sample Output:
The
T
h
e
fox
f
o
x
the
t
h
e
dog
d
o
g
over
o
v
e
r
lazy
l
a
z
y
quick
q
u
i
c
k
brown
b
r
o
w
n
jumps
j
u
m
p
s