The problem is with the extract function. I can't figure out how to extract each word from the input stream.
// Program summary
// This program is made to take a string of input from the user
// Then the functions take apart the string word by word and reverse it
// the original string and the new string are then outputed to the screen
#include<iostream>
#include<string>
#include<cstring>
#include <stdio.h>
#include <string.h>
using namespace std;
class StringModify
{
public:
void get_data();
//takes a line of input fromt the user
void extract_word();
//extract each word fromt he input line
string reverse_word(const string& s);
//return a string which is reverse of s
void swap(char& v1, char& v2);
//interchanges value of v1 and v2
void append(const string& reverse_word);
//puts together each reversed word with the whitespaces to get formatted_line
void display();
//displays both inout line and formatted_line
int main()
{
StringModify data1;
data1.get_data(); // function calls for memebr functions
data1.extract_word();
data1.display();
return 0;
}
void StringModify::get_data() //function to get the original string from the user
{
cout << "Enter the string: ";
getline(cin, line);
}
void StringModify::extract_word() //function to extract each word in the original string then reverse and append them
{
char line;
char *p1;
p1 = strtok(line, " ");
while(p1 != " ")
{
p1 = strtok (NULL, " ");
}
reverse_word(const line); //function call for reverse_word function
append(const line); //function call for reverse_word function
}
string StringModify::reverse_word(const string& s) //function to reverse the words in the inputed string
{
int start = 0;
int end = s.length();
string line(s);
while (start < end)
{
end--;
swap(line[start], line[end]);
start++;
}
return line;
}
void StringModify::swap(char& v1, char& v2) //function to swap the stringd
{
char line = v1;
v1 = v2;
v2 = line;
}
void StringModify::append(const string& reverse_word) //function that appends the original string to formatted_string
{
formatted_line.append(line);
}
void StringModify::display() //function to display both the original function and the formatted string
{
cout << "original string: " << line << endl;
cout << "formatted string: " << formatted_line << endl;
}
hi,
I think I have got the code working with a few minor change to
- extract_word()
- append()
extract_word()
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void StringModify::extract_word() //function to extract each word in the original string then reverse and append them
{
char *p1;
p1 = strtok(&line[0], " ");
while(p1 != NULL)
{
append(reverse_word(p1));
p1 = strtok (NULL, " ");
}
}
append()
1 2 3 4 5 6
void StringModify::append(const string& reverse_word) //function that appends the original string to formatted_string
{
formatted_line.append(reverse_word);
formatted_line.append(" ");
}