Write a C++ program in which, read a c-string sentence as input from File. Now your task is to reverse each word of sentence
#include <iostream>
#include <fstream>
#include <cstring>
#include <algorithm>
int main() {
std::ifstream in("file.txt");
char buffer[256];
in.getline(buffer, 256);
auto length = strlen(buffer);
for(size_t left = 0, right = 0; right <= length; right++) {
if(!isalpha(buffer[right]) || right == length) {
for(size_t i = left, j = right - 1; right && i <= j; i++, j--) {
std::swap(buffer[i], buffer[j]);
}
// skip spaces
while(right < length && buffer[right] == ' ') right++;
left = right;
}
}
std::cout << buffer << '\n';
return 0;
}
Comments
Leave a comment