C++: Counting the frequency of ASCII characters in file [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am a beginner to C++ and have been pondering this problem for quite a while, but I'm finding myself unable to come up with a solution and was hoping I could find some direction here.
I have an input file that will contain any number of ASCII characters (ex: hello, world; lorem ipsum; etc.). My program will read this file and count the frequency of each ASCII character, outputting the end counts when EOF is reached. I believe I need to use array[128] for the counters, but besides that, I'm totally stuck.
Here's what I have so far (it's not much and only reads the characters from the file):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
ifstream inputFile;
string infile;
char ch;
//char ascii;
//int asciiArray[128] = {0};
// Gets input filename from user, checks to make sure it can be opened, and then
// gets output filename from user.
cout << "Please enter your input filename: ";
cin >> infile;
inputFile.open(infile.c_str());
if (inputFile.fail())
{
cout << "Input file could not be opened. Try again." << endl;
exit(0);
}
// Gets the first character of the input file.
inputFile.get(ch);
while(!inputFile.eof())
{
inputFile.get(ch);
}
// Closes the input file
inputFile.close();
return 0;
}
Any direction or help would be greatly appreciated. I have a feeling I will need to use pointers to solve this...but I've just barely started covering pointers, so I'm very confused. Thanks!
Edit: I removed some variables and it's working now, looks like I forgot them there while I was brainstorming. Sorry for leaving it unworking and not mentioning why; I won't do that again!

You should write your loop as:
while(inputFile >> ascii)
{
asciiArray[ascii]++;
}
Note that I don't directly check for eof in the loop condition since that's almost always wrong.
Also you should be sure that your file is indeed written with ascii characters only. Since any character outside the ascii range would result in an out of bounds access to the asciiArray.

In regular Ascii you have 128 chars... of which each char can be evaluated as an int.
That is the key in solving this puzzle.
Just remember you have 128 possible chars, an array with 128 values, and each char represents a number from 0-127.
Also recall that you can do stuff like this:
int i = 97;
char a = i;
char b = a + 1;
cout << (int)i << (int)a << (int)b << endl;
// 979798
cout << (char )i << (char )a << (char )b << endl;
// aab
cout << i << a << b << endl;
// 97ab
As far as pointers go, the only way I would see them as being used is if you used pointer notation instead of array notation while manipulating your variable asciiArray

Related

c++ variable reassignment gets ignored by code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am not a professional programmer but after getting some experience in easy languages like python or matlab, I need to make a little program in C++. For this I try to read user input until the user inputs something sensible - however, this loop never terminates due to my control variable (test2) never being reassigned, even though the corresponding code block is entered. Let me explain in detail:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Header.h"
using namespace std;
int test2; //variable to stay 1 until user has entered suitable input
string input2[2]; //storage for input strings
int MinimalTest() {
test2 = 1; //control variable is set one
cout << "Enter a string." << endl;
do {
//we will enter a string at least once, and we exit this loop only when the input is suitable
std::string line; //complicated input part - a simple getline() command led to weird behaviour
std::getline(std::cin, line);
std::stringstream linestream(line);
linestream >> input2[i];
cout << "input: " << input2[i] << " test: " << test2 << "input bool: " << input2[i].empty() << endl; //this is just for troubleshooting
if (input2[i].empty()) {
//if the user entered an empty string, he needs to do it again
cout << "Your string is empty. Please enter a valid string (non-empty)." << endl;
}
else {
//if he entered a valid string, we can continue with the next input
cout << "I am here." << endl; //This is for trouble shooting. This code block is entered and executed since this gets printed.
test2 = 0;// this gets ignored for some reason. Hence, the loop never terminates.
}
}(while (test2 = 1);
}
So the first loop never terminates. Test2 never gets reassigned to 0, even though the else command is executed. This boggles my mind tbh - it is just a simple assignment operator on an int. Possible output looks like this (Note how I still got a second problem: strings with a space inside get cut off. I would appreciate any feedback on that as well, even though I try to trouble shoot one thing at a time and this post is not aimed at this problem):
Output example
Thank you very much for your consideration!
All the best,
A very confused newbie.
Change your while condition to test2 == 1
test2 = 1 is an assignment, setting the value to 1.

Why the loop only run one time? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to do a phone Sys and I used a while loop in the main{}. I don't know why it only runs one time, it suppose to run infinite time unless I give it command to stop.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void record(string name, int phoneNum, int count);
// main
int main() {
cout << " Welcome to use the Phone Contact Systerm " << endl;
string name;
int phoneNum;
int count = 0;
string signToStop;
cout << " Please enter name and phone number " << endl;
while ( cin >> name >> phoneNum){
cout << " If you want to start the program, enter start " << endl;
cout << " If you want to quit the program, enter quit " << endl;
cin >> signToStop;
if (signToStop == "start"){
record(name, phoneNum, count);
}
else if ( signToStop == "quit" ){
break;
}
count++;
}
}
// record all name info into Name set and record all phone numbers into PhoneNum set
void record(string name, int phoneNum, int count){
string Name[] = {};
int PhoneNum[] = {};
Name[count] = {name};
PhoneNum[count] = {phoneNum};
// now start to record all the info into .txt document
ofstream phoneFile;
phoneFile.open("contact.txt");
phoneFile << name << " " << phoneNum << endl;
}
The result is:
Welcome to use the Phone Contact Systerm
Please enter name and phone number
Molly 5307659229
Process finished with exit code 0
Maybe try ulong int for the phone number, it might be too long. Also I might add that I am a bit confused, as your function record() has a 3rd argument that has no default argument. Your problem might lie there too. As without a default you need to put the argument in when it is used.
As spectras said, a phone number is not really an integer, and so it's not a "number" in the programming (or even mathematical) sense.
It's more like a sequence of digits; that is, a string.
You have two problems when you try to interpret it as an int:
Your int type is too small for the value (this is what's causing your loop to end)
Leading zeroes are not meaningful (at best, it's used to flip into octal mode, which is not what you wanted).
I'd instead read it as a string. You can still validate it later, like "is every character a digit?".

How to print characters with spaces as a string in C++ [duplicate]

This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 8 years ago.
The code is not giving desired output
when I type in a string example "Ben Parker", the output is "Goodmorning, Ben" and not the entire name("Ben Parker") what seems to be the problem?
#include <iostream>
#include <stdlib.h>
#include <cstring>
int main() {
char your_name[20];
std::cout << "Enter your name: ";
std::cin >> your_name;
std::cout << "Goodmorning, ";
std::cout.write (your_name, strlen(your_name)) << std::endl;
return 0;
}
SOLUTION
This was a very old question when I just began programming.
The entire character array can be read and printed with a for loop, or better a string type variable can be used, since it is C++.
using string your_name; seems to fix the problem, which can be then printed with a simple std::cout << your_name << endl;
You probably put a space in between "Ben" and "Parker" in input. This would cause the cin logic to believe it had an answer after seeing the space following "Ben". You will probably want to read an entire line at a time to get past that problem. See this page for an example.

howto get with scanf a string ( char * ) from a user input, delimited by double quotes and containing spaces [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am quite noob with c and c++, and I am stucked trying to read a user input delimited between double quotes for a program I have to deliver to my algorithm class.
The entry would be in this form: "something like this, with spaces, and delimited by this two double quotes".
What I need to get from that is the string ( char * ) contained between the delimiters.
Unfortunatelly I have been trying without luck to solve this small issue...
The development environment is a virtualized Windows 7 and the ide (both are requirements from the teacher) is DEVC++
Anyone could give a hint or help me out? I am stucked with this and I am running out of time.
thanks in advance!
Assuming you have a stream where the current character is a double quote, you can just
ignore() the current character.
getline() using '"' as the delimiter.
Here is code which skips leading space, verifies that the next character is a '"' and, if so, reads the value into str:
std::string str;
if ((in >> std::ws).peek() == '"' && std::getline(in.ignore(), str, '"')) {
std::cout << "received \"" << str << "\"\n";
}
If I understood the question correctly, then the following suits you. This approach will eliminate every punctuation.
#include <string>
#include <algorithm>
#include <iostream>
int main ()
{
std::string input ;
std::cout << "Please, enter data: ";
std::getline (std::cin,input);
input.erase( remove_if(input.begin(), input.end(), &ispunct), input.end());
std::cout << input << std::endl;
std::cin.get();
return 0;
}
This is the result.
>Please, enter data: There' ?are numerous issues.
There are numerous issues
This approach is exactly what you are looking for by using strtok
#include <stdio.h>
#include <iostream>
int main()
{
char sentence[] = "\"something like this, with spaces, and delimited by this two double quotes\"";
char * word;
std::cout << "Your sentence:\n " << sentence << std::endl;
word = strtok (sentence,"\"");
std::cout << "Result:\n " << word << std::endl;
return 0;
}
The result
Your sentence:
"something like this, with spaces, and delimited by this two double quotes"
Result:
something like this, with spaces, and delimited by this two double quotes

C++, Text to ASCII while-loop error

I've come this far without asking for help, but I've got a problem that I can't seem to fix. I like cryptology, so now that I am learning C++, I want to make programs to encrypt and decrypt strings. I read that the best way is to convert the text to ASCII and go from there, so here is a simple program I made in C++ to try and convert a char variable to ASCII:
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main()
{
char strString[1000];
cout<<"Enter you message:"<<endl;
cin>>strString[1000];
string strEncrypt;
int a = 0;
while (strString != '\0')
{
int b = (int)strString[a];
strEncrypt.at(a) = b; //This is where I'm getting an error.
a++;
}
cout<<"Encrypted message:"<<endl;
cout<<strEncrypt<<endl;
}
So, I've tried all 3 things I know to do to troubleshoot (Google, check for missing simicolons, and make sure I'm doing == not =, but this is just something I don't know how to do, not something I'm forgetting (I hope). So, any help would great!
You don't have to change the characters to ASCII they already are. Chars are basically the same as integers in memory.
Now to your question; . If you want to set a character in a string you can do that like this
string[index] = b;
Another thing to be careful for in your code. You are using cin to read the string from the user. This will not let you read messages that have spaces in them and will only read the first word. For example, if the user enters "Love Crypto" cin will only read "Love" and "Crypto" will be ignored. To get the entire line, use getline instead.
As for looping over characters in a string, it's better to do it as follows:
for(int i = 0; i < strString.length(); i++)
{
strString[i] = bla;
}
Again, you're code isn't actually doing anything. It is only reading a letter and then storing a "letter" in another string.
string::at() throws exception if the index passed to at() is out of range. So, if you are getting runtime error then it's expected. Because, your string strEncrypt is initialized to "" and thus the size is 0.
You may try
strEncrypt.reserve(strlen(strString));
Easiest way to actually make the code you have work is change this line strEncrypt.at(a) = b; to this strEncrypt += b; Which will add the characters to the empty string strEncrypt.
Your code doesn't make much sense though as char types are already ascii. You'll have to explain more about what kind of encrypting you are trying to do and maybe we can point you in the right direction.
EDIT: After thinking about what you're trying to do a bit more based on the code you have it seems like you want to print the numeric ascii value of characters. You can do that with just a cast like this:
string input;
cout << "Enter you message:" << endl;
// handle spaces in the message
getline(cin, input);
cout << "String chars as ascii values:" << endl;
cout << "Char: " << "ASCII Code:" << endl;
for (int i = 0; i < input.length(); ++i)
{
// casting the char to an int with (int) will print the ascii code
cout << input[i] << " " << (int)input[i] << endl;
}
On top of the fact that your input is already in ASCII, keep in mind that doing cin >> strString[1000] doesn't limit the input captured to the length of your buffer unless you specifically specify the number of characters to capture for the stream object using setw() or setting it's ios_base::width data member. So your method right now risks buffer overflows.
Secondly, the form of cin >> that you're using will not capture the entire line of input. Instead it will stop at the first white-space or any other delimiting character (or end-of-file if that is reached first). In your case, if you are entering a line like "Hello World", then the syntax you're using will only capture "Hello" and drop "World".
A much better idea would be to use the getline() function with a std::string object if you are wanting to capture a line of input to a string and remove the delimiting newline character without risking buffer overflows ... for instance:
string strString;
getline(cin, strString);
Apart from advises given, when receiving this kind of run-time errors use Cppcheck utility.
It will give you the answer: "Message: Array 'strString[1000]' index 1000 out of bounds".