how to print out more than a character at once - c++

I saved this word "abs" in a text file and i'm trying to make a code that can print the three characters at once in another file .. not like that
while (content[i] == 'a')
{
fout<<"a";
break;}
while (content[i] == 'b')
{
fout<<"b";
break;}
while (content[i] == 's')
{
fout<<"s";
break;}
here is the code i wrote but it doesn't print anything out..
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout("E:\\hoss.txt");
ifstream file("E:\\test.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
while (content[i] == 'ab')
{
fout<<"ab";
break;}
}}
system("pause");
return 0;
}
anyone can help??

int main()
{
ofstream fout("E:\\hoss.txt");
ifstream file("E:\\test.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
if((content[i] == 'a') && (content[i+1] == 'b'))
{
fout<<"ab";
break;
}
}
}
system("pause");
return 0;
}

You have no code to print anything out. You just keep adding to the buffer, but you never flush the buffer. Get rid of the system("pause"); and just let the program end. Ending the program flushes all buffers.
while (content[i] == 'ab')
This is pretty baffling. Did you really mean ab as a character constant?

Related

Validating Password Loop using control structures

I am trying to create a program where a string (password) is read from the terminal.
the password has to be atleast 8 char long, must have an upper and lower case letter, a digit and no space.
here's the code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string pw;
char i;
bool hasLow=0, hasUpp=0, hasdigit=0, hasspace=0, status=0;
do {
cout<<"What will be your password?"<<endl;
getline (cin,pw);
for (int i = 0; i < pw.length(); i++) {
if (isupper(pw[i])) hasUpp =1;
if (islower (pw[i])) hasLow=1;
if (isdigit(pw[i])) hasdigit=1;
if (!(isspace (pw[i]))) hasspace=1; }
cout<<"password is invalid. Please try again."<<endl;
}
while ( (hasUpp) && (hasLow) && (hasdigit) && (hasspace) && (pw.length() >= 8));
{cout<<"Password is valid";} }
I can't get the do while loop to work (has to be do while) and the password is accepted even if there is a space
You are not resetting your bools on each loop iteration. Your loop condition is wrong. And your invalid message is in the wrong place.
Try this instead:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string pw;
char ch;
bool hasLow, hasUpp, hasdigit, hasspace;
do {
cout << "What will be your password?" << endl;
getline (cin, pw);
hasLow = hasUpp = hasdigit = hasspace = false;
for (size_t i = 0; i < pw.length(); ++i) {
ch = pw[i];
if (isupper(ch)) hasUpp = true;
else if (islower(ch)) hasLow = true;
else if (isdigit(ch)) hasdigit = true;
else if (isspace(ch)) hasspace = true;
}
if ((hasUpp) && (hasLow) && (hasdigit) && (!hasspace) && (pw.length() >= 8))
break;
cout << "password is invalid. Please try again." << endl;
}
while (true);
cout << "Password is valid";
}
Online Demo

I am getting a segmentation fault in this code and can't understand why?

I am trying to code a program where it takes a program as an input and prints out all the comments written in that program in a separate line.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
while(getline(cin,str)) {
int i;
// cout<<str;
for(i=0;str[i]!='/' && str[i+1] !='/';i++);
//cout<<i;
for(i;str[i]!='\n';i++) {
// cout<<i;
cout<<str[i];
}
cout<<endl;
}
return 0;
}
I am getting a segmentation fault in this code and I can't understand why. This is part of a code of a problem in hackerrank https://www.hackerrank.com/challenges/ide-identifying-comments/copy-from/12957153
As commented in your question your code is wrong. First you are treating std::string object, returned by getline, as character array. Secondly your for loops never end if there is no // or \n found in input string. So obviously it will crash. Below is the modified code.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
while(getline(cin,str)) {
int i;
// cout<<str;
size_t len = str.length();
const char *cstr = str.c_str();
for(i=0; (cstr[i]!='/' && cstr[i+1] !='/' && i < len); i++)
//cout<<i;
for(; cstr[i]!='\n' && i < len;i++) {
// cout<<i;
cout<<cstr[i];
}
cout<<endl;
}
return 0;
}
int main() {
while(getline(cin,str)) {
int i, len = str.size();
//always make sure that you are not accessing
//contents after your string has ended
for(i=0; i < (len - 1) && !(str[i] == '/' && str[i+1] == '/'); i++);
//note that i here might be the last alphabet
//if there's no comment
if(i < len && str[i] != '/')
i++;
//checking if str[i] != '\n' is not a good idea
//as c++ stl strings are not temrinated by '\n'
if(i < len) {
for(; i < len; i++)
cout << str[i];
cout << endl;
}
}
return 0;
}
Also note that both of the following codes won't terminate at the 4th character, c++ stl strings are not terminated by these characters.
string str = "hahahaha";
str[4] = '\n';
cout << str;
str[4] = '\0';
cout << str;
This is much easier to write and probably much faster than the other solutions to date.
#include <iostream>
int main()
{
std::string str;
while (std::getline(std::cin, str))
{
size_t loc = str.find("//");
if (loc != str.npos)
{
std::cout << str.substr(loc + 2)<< std::endl;
}
}
return 0;
}
It is also wrong.
Here is a nice, clean, and simple state machine version. Also pretty close to worst-case for speed. Thing is it's closest to being right, even though it is also wrong.
#include <iostream>
enum states
{
seeking1,
seeking2,
comment
};
int main()
{
std::string str;
while (std::getline(std::cin, str))
{
states state = seeking1;
for (char ch:str)
{
switch (state)
{
case seeking1:
if (ch == '/')
{
state = seeking2;
}
break;
case seeking2:
if (ch == '/')
{
state = comment;
}
else
{
state = seeking1;
}
break;
case comment:
std::cout << ch;
break;
}
}
if (state == comment)
{
std::cout << std::endl;
}
}
return 0;
}
Why are these approaches all wrong? Consider the line
cout << "Hi there! I am \\Not A Comment!" << endl;`
You can't just look at the \\, you also need the context. This is why the state machine above is the better option. It can be modified to handle, at the very least, states for handling strings and block comments.

How to rewrite/overwrite strings/lines in a text file?

I'm totally new in c++ and having problem with a particular portion of my program. As no one to help me in real, I have dared to ask it here. If a text file includes this line "hELp mE", it should be rewritten/overwritten as "HelP Me" in the same exact text file. What i know is that, I might need to use ofstream for the overwriting but i'm very confused about how it should be done. I have tried for about 2 hours and failed. Here is my half completed code which is only able to read from the file.
int main()
{
string sentence;
ifstream firstfile;
firstfile.open("alu.txt");
while(getline(firstfile,sentence))
{
cout<<sentence<<endl;
for(int i=0;sentence[i] !='\0';i++)
{
if((sentence[i] >='a' && sentence[i] <='z') || (sentence[i] >='A' && sentence[i] <='Z'))
{
if(isupper(sentence[i]))
sentence[i]=tolower(sentence[i]);
else if(islower(sentence[i]))
sentence[i]=toupper(sentence[i]);
}
}
}
return 0;
}
It's works good:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string sentence;
ifstream firstfile;
firstfile.open("alu.txt");
while(getline(firstfile,sentence))
{
cout<<sentence<<endl;
for(int i=0; sentence[i] !='\0'; i++)
{
if((sentence[i] >='a' && sentence[i] <='z') || (sentence[i] >='A' && sentence[i] <='Z'))
{
if(isupper(sentence[i]))
sentence[i]=tolower(sentence[i]);
else if(islower(sentence[i]))
sentence[i]=toupper(sentence[i]);
}
}
}
firstfile.close();
cout<<sentence<<endl;
ofstream myfile;
myfile.open ("alu.txt");
myfile<<sentence;
myfile.close();
return 0;
}
according to your code, I simply just close() your read mode and open open() mode & take the sentence
this link is may be help to you Input/output with files in C++
Follow #πάντα ῥεῖ solution, you could using ifstream to read the contents in the specific file, then judge and change UPPER/lower for every character. At the end, using ofstream to overwrite the original file.
Wish is helpful.
You can use fstream to do in-place rewriting in C++. This will replace all lowercase with uppercase and vice-versa, character by character.
#include <iostream>
#include <fstream>
#include <locale>
int main()
{
std::locale loc;
std::fstream s("a.txt");
char next;
int pos = 0;
while((next = s.peek()) != EOF) {
if(islower(next,loc))
next = toupper(next,loc);
else if(isupper(next,loc))
next = tolower(next,loc);
s.seekp(pos);
s.write(&next,1);
pos++;
}
return 0;
}

C++ Dictionary Compare with multiple strings and files

I am trying to write a program that will compare an input file to a dictionary file filled with tons of words. After comparing the words, I want to output the words that are spelled incorrectly. Here is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
void trim(string s)
{
size_t p = s.find_first_not_of(" \t");
s.erase(0, p);
p = s.find_last_not_of(" \t");
if (string::npos != p)
s.erase(p+1);
}
int main()
{
ifstream input;
ifstream words;
input.open("/Users/jordan/Desktop/CS60/Word_dictionary_check/input.txt");
if(input.fail())
{
cout<<"Input file opening failed";
exit(1);
}
words.open("/Users/jordan/Desktop/CS60/Word_dictionary_check/words.txt");
if(words.fail())
{
cout<<"Words file opening failed";
}
vector <string> wordCheck;
vector <string> misspelledWord;
string temp = "";
while(!input.eof())
{
input>>temp;
wordCheck.push_back(temp);
}
ofstream output;
output.open("/Users/jordan/Desktop/CS60/Word_dictionary_check/output.txt");
if(output.fail())
{
cout<<"Output file opening failed";
exit(1);
}
for(int j = 0; j < wordCheck.size(); j++)
{
bool dontprint = false;
while(!words.eof())
{
words>>temp;
if(temp == wordCheck[j])
{
dontprint = true;
}
}
if(dontprint == false)
{
misspelledWord.push_back(wordCheck[j]);
}
}
for(int i = 0; i < misspelledWord.size() ; i++)
{
output<<misspelledWord[i]<<endl;
}
return 0;
}
I believe something with whitespace or with the comparing of strings is a problem. Thanks for helping me out!
I can see few obvious problems. I have added comments. This should solve your problem but I am not going to write code for you.
for(int j = 0; j < wordCheck.size(); j++)
{
bool dontprint = false;
//Make your words file pointer to point to start of file. USe seek function
while(!words.eof())
{
words>>temp;
if(temp == wordCheck[j])
{
dontprint = true;
//You can break here. As once word is found, you don't need to check the word file further
}
}
if(dontprint == false)
{
misspelledWord.push_back(wordCheck[j]);
}
}

I want an array of cstrings separated by white space

I am trying to get user input and put it into an array of cstrings separated by a space. When I print the array to the screen though I get nothing. I am sure I am doing something stupid, but I have been stuck trying different ways for a while. Any help would be appreciated. Here is the code.
#include <iostream>
#include <cstring>
using namespace std;
void stuff(char command[][25], int length)
{
char ch;
for(int i = 0; i < length; i ++)
{
int b = 0;
cin.get(ch);
while(!isspace(ch))
{
command[i][b++] = ch;
cin.get(ch);
}
command[i][b] = '\0';
cout << endl;
}
}
int main()
{
char cha[10][25];
char ch;
int len = 0;
while(ch != '\n')
{
cin.get(ch);
if(isspace(ch))
{
len++;
}
}
stuff(cha,len);
for(int i = 0; i < len; i++)
{
cout << cha[i] << endl;
}
cout << len << endl;
return 0;
}
a) ch is undefined when you first test it with while (ch != '\n'). Initialize it to zero or something.
b) You don't write any values into cha in the while loop. Perhaps something like:
int pos = 0;
while(ch != '\n') {
cin.get(ch);
if (isspace((unsigned)ch)) {
if (pos > 0) {
++len;
pos = 0;
}
}
else {
cha[len][pos] = ch;
++pos;
}
}
c) You are reading the stream again in stuff(...) but have already consumed what you wanted to get from the stream in main().
d) This code suffers from a number of buffer overrun and stack corruption opportunities. perhaps use a std::vector<std::string> instead. If it runs out of memory it will throw an exception rather than make a mess on the stack.
Perhaps something like this (untested):
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main()
{
typedef std::vector<std::string> strvec;
strvec cha;
std::string s;
char ch = 0;
while(ch != '\n') {
cin.get(ch);
if (isspace((unsigned)ch)) {
if (!s.empty()) {
cha.push_back(s);
s.clear();
}
}
else {
s.push_back(ch);
}
}
// don't need to call 'stuff' to null terminate.
for (strvec::iterator i = cha.begin(); i != cha.end(); ++i) {
cout << *i << endl;
}
cout << cha.size() << endl;
}
This could be a little more efficient than it is but hopefully it is easy to understand.
You are reading the whole input in the while cycle in the main to read length(number of strings), but you never store it. Later on in stuff cin.get will read nothing. Maybe store the input in cha during the first cycle?