I've been working on this program for a very long time now and I think I'm close to being done. However, my code is outputting something strange and I cannot find the issue.
Expected output:
This is a happy tESt to check if my reader works!
An happy alligator was AT tHe happy park and a happy a cow blew its nose in a happy scarf. are you an happy Octagon THe
Actual output:
This is a tE happySt to check if my reader works!
a happy
THe Happy
How can I make the following code behave as I expect?
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
#include <locale>
using namespace std;
void
usage(char *progname, string msg){
cerr << "Error: " << msg << endl;
cerr << "Usage is: " << progname << " [filename]" << endl;
cerr << " specifying filename reads from that file; no filename reads standard input" << endl;
}
string capitalization(string word,string adj){
for(int i = 0; i <= word.length(); i++){
if(isupper(word[i])){
for(int j = 0; j <= adj.length(); j++){
adj[j] = toupper(adj[j]);
return adj;
}
}
else if(isupper(word[0])){
for(int j = 0; j <= adj.length(); j++){
adj[j] = tolower(adj[j]);
return adj;
}
}
else{
for(int j = 0; j <= adj.length(); j++){
adj[j] = tolower(adj[j]);
return adj;
}
}
}
}
int main(int argc, char *argv[]){
string adj;
string file;
cin >> adj;
cin >> file;
string line;
string articles[14] = {"a","A","an","aN","An","AN","the","The","tHe","thE","THe","tHE","ThE","THE"};
ifstream rfile;
rfile.open(file.c_str());
if(rfile.fail()){
cerr << "Error while attempting to open the file." << endl;
return 0;
}
string::size_type pos;
string word;
string words[1024];
while(getline(rfile,line)){
istringstream iss(line);
for(int i = 0; i <= line.length(); i++){
iss >> word;
words[i] = word;
for(int j = 0; j <= 14; j++){
if(word == articles[j]){
string article = word;
iss >> word;
pos = line.find(article);
//cout << pos << endl;
string adjec = capitalization(word,adj);
int position = (pos + word.length());
line.insert(position, " " + adjec);
continue;
}
}
}
cout << line << "\n";
}
}
This may not fix any of your problems, but...
The logic in these lines is wrong.
istringstream iss(line);
for(int i = 0; i <= line.length(); i++){
iss >> word;
Let's say your line is
This is a test.
For this line, line.length() is 15 but there aren't 15 words. What you need is
istringstream iss(line);
while ( iss >> word ) {
Related
vector<string> names;
// Read names from file book.txt
ifstream in("movie.txt");
if (!in.is_open())
cout << "Unable to open file\n";
string word;
while (getline(in, word))
names.push_back(word);
int pos(0), i(0), j(0);
string temp;
for (size_t i = 0; i < names.size(); i++)
{
j = i;
while (j >= 0 && names[j] < names[j - 1])
{
temp = names[j];
names[j] = names[j - 1];
names[j - 1] = temp;
j--;
}
}
// Loop to print names
for (size_t i = 0; i < names.size(); i++)
cout << names[i] << '\n';
Not sure where the error is coming from as it still runs, but as i try
and execute the file it says "Debug assertion error." Any help?
If you want to read the names then try this it works
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char **argv)
{
vector<string> names;
ifstream in("movies.txt");
if (!in.is_open())
cout << "Unable to open file\n";
string word;
while (getline(in, word))
names.push_back(word);
for (auto i : names)
cout << i << '\n';
return 0;
}
I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:
For some reason I am getting zero values in my vector when I try to read from a txt file.
Here is my code:
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
while (read >> n){
source.push_back(n);
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
The txt file is rather long but the format is:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
Here is reading one by one:
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main(){
ifstream read("e:\\problem13.txt");
vector<int> source;
char n;
while (read >> n){
source.push_back(n - '0');
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << endl << "Size: " << source.size() << endl << "Finished.";
}
But i recommend you reading line by line or if the file is no so big reading all in an std::string and process the string (reading from file is expensive).
In order to store each digit as an int, read each line and store it in a string. Then process each line.
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
string line;
while (read >> line){
string::iterator iter = line.begin();
string::iterator end = line.end();
for ( ; iter != end; ++iter )
{
n = (*iter) - '0';
source.push_back(n);
}
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
I open a txt file using argc, argv, and getline. I did that properly, but now I have to get the number of words per line (the number of lines is not known before) and I must output them in reverse. Meaning from the bottom line to the top line. Any help is appreciated. This code outputs the number of words in the file:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
if(argc < 1){
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if(ifile.fail()){
cerr << "Could not open file." << endl;
return 1;
}
int n;
ifile >> n;
cout << n;
int numberOfWords = 0;
string line;
for(int i = 0; i <= n; i++){
getline(ifile, line);
cout << line << endl;
}
size_t i;
if (isalpha(line[0])) {
numberOfWords++;
}
for (i = 1; i < line.length(); i++) {
if ((isalpha(line[i])) && (!isalpha(line[i-1]))) {
numberOfWords++;
}
}
cout<<"The number of words in the line is : "<<numberOfWords<<endl;
return 0;
}
To find the number of words per line you would use std::getline() to iterate over each line and use std::stringstream to extract each chunk of whitespace-separated input. Then you would iterate over each chunk of input and check to see if each character is alphabetic:
int numberOfWords = 0;
for (std::string line, word; std::getline(ifile, line); )
{
std::istringstream iss(line);
while (iss >> word)
{
bool alpha = true;
for (char c : word)
if (!std::isalpha(c)) alpha = false;
if (alpha) ++numberOfWords;
}
std::cout << "Number of words on this line: " << numberOfWords << std::endl;
numberOfWords = 0;
}
I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;
[0][0] = 0, [0][1] = 0, etc.
The data file contains values like;
0.000579, 27.560021, etc.
int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");
for(int i = 0; i < rows; i++){
for(int j = 0; j < 2; j++){
in >> dataVec[i][j];
cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
}
}
in.close();
It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)
Try this solution, it works according to your specs:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ifstream infile;
char cNum[10] ;
int rows = 1;
int cols = 2;
vector<vector<float > > dataVec(rows,vector<float>(cols));
infile.open ("test2.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < 2; j++)
{
infile.getline(cNum, 256, ',');
dataVec[i][j]= atof(cNum) ;
cout <<dataVec[i][j]<<" , ";
}
}
}
infile.close();
}
else
{
cout << "Error opening file";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
void write(int m, int n)
{
ofstream ofs("data.txt");
if (!ofs) {
cerr << "write error" << endl;
return;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
ofs << i+j << " ";
}
void read(int m, int n)
{
ifstream ifs("data.txt");
if (!ifs) {
cerr << "read error" << endl;
return;
}
vector<float> v;
float a;
while (ifs >> a) v.push_back(a);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cout << "[" << i << "][" << j << "] = "
<< v[i*n+j] << ", ";
}
int main()
{
write(2,2);
read(2,2);
return 0;
}