Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have tried lots of solutions to convert a char to Ascii. And all of them have got a problem.
One solution was:
char A;
int ValeurASCII = static_cast<int>(A);
But VS mentions that static_cast is an invalid type conversion!!!
PS: my A is always one of the special chars (and not numbers)
A char is an integral type. When you write
char ch = 'A';
you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
Uhm, what's wrong with this:
#include <iostream>
using namespace std;
int main(int, char **)
{
char c = 'A';
int x = c; // Look ma! No cast!
cout << "The character '" << c << "' has an ASCII code of " << x << endl;
return 0;
}
You can use chars as is as single byte integers.
Related
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 5 years ago.
Improve this question
Hello i'm from Indonesia. and i'm verry beginner on C++ programming. I have some problem when i learn about string on C++ . First i declared array of char and i want to initialize a value separately in different command. After i initialize the value my compiler say "Invalid Argument".
#include <iostream>
using namespace std;
int main() {
char Name[5];
Name = "Luke";
cout<<"Character 0 :"<<Name[0]<<endl;
cout<<"Character 1 :"<<Name[1]<<endl;
cout<<"Character 2 :"<<Name[2]<<endl;
cout<<"Character 3 :"<<Name[3]<<endl;
cout<<"Character 4 :"<<Name[4]<<endl;
return 0;
}
sorry if my english is bad :(
A character array(including a C string) can not have a new value assigned to it after it is declared.
The C++compiler interprets these assignment statements as attempts to change the address stored in the array name, not as attempts to change the contents of the array.
However you can use
char name[] = "Luke";
A char[] can't be assigned with a string with the = operator, except for on its initialization. That's why char Name[5]; Name = "Luke"; is invalid while char Name[5] = "Luke"; is.
Assigning strings to char[] can be done with strcpy() / memcpy()-like functions.
So you have two ways of action (assuming you want to work with char[]):
char Name[5] = "Luke";
char Name[5]; strcpy(Name, "Luke"); /* don't forget to #include <string.h>*/
Just for sake of education (since the other answers are on-point to answer the question), here's how I would have written your code to do nearly the same thing.
The changes demonstrate:
used a more appropriate container (a string instead of a char[])
checked for access overruns
moved "one unit of work" into its own subroutine
Code was compiled as C++17 with /usr/bin/clang++ -Weverything -Wno-c++98-compat --std=c++1z:
#include <cstddef>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void PrintCharAtPos(string const& s, string::size_type pos);
int main() {
auto Name = string{"Luke"};
PrintCharAtPos(Name, 0);
PrintCharAtPos(Name, 1);
PrintCharAtPos(Name, 2);
PrintCharAtPos(Name, 3);
PrintCharAtPos(Name, 4);
return EXIT_SUCCESS;
}
void PrintCharAtPos(string const& s, string::size_type pos) {
if (pos < s.length())
cout << "Character " << pos << " : " << s[pos] << endl;
else
cout << "Character " << pos << " : (out of bounds)" << endl;
}
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 6 years ago.
Improve this question
This shows no output:
int x = 10;
cout<<"Hello C++ " + x ;
But this does show output:
int x = 10;
cout<<"Hello C++ ";
cout<<x<<endl;
What is the problem? They seem exactly the same.
BTW I'm Using Visual C++ 6.0 On Visual Studio 2010 .
Because that's not how to use streams, or strings.
The + operator is for:
adding two numbers together, or
concatenating two std::strings together.
Here you have a string literal and a number. The + operator is not compatible with those.
(What you actually end up doing is "adding" 10 to the pointer representing the string literal; as it happens, because your string is ten characters long, that leaves the pointer exactly where your string literal's NULL terminator is, so it is like trying to print "".)
The correct approach, as you have yourself found via the second example, is to use the stream's << operator again.
cout << "Hello C++ " << x;
"Hello C++ " + x ;
makes no sense. You add 10 to the address of the string "Hello C++" and then std::cout should do an output of this what is on address "Hello C++" + 10.
So this makes simply no sense.
std::cout is part of the iostream.
How do you append an int to a string in C++?
I suggest you look closely at the above post to tackle your problem.
In C or C++, concatenation is done best using string streams. But to specifically answer your question:
This C++ Code Shows No Output:
int x = 10;
cout<<"Hello C++ " + x ; //uses "+" as you are trying to concatenate an "int" to some output to the stream
But This One which Shows An Output:
int x = 10;
cout<<"Hello C++ "; //output directly to stream
cout<<x<<endl; //same here, no concatenation
What's the problem then, are they exactly the same ?
The problem is with "+" concatenation to the stream and NO, they aren't the same! :)
Try using instead of: cout<<"Hello C++ " + x ;
cout<<"Hello C++ " << x ;
int x = 10;
cout << "Hello world!" << ++x;
return 0;
If you want to increment a variable, you should use ++x. If you want to decrement it, use --x.
And, if you want to show a variable next to another one, or next to another string, use << between them.
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 want to take argv[(2 in this example)], store it into vector and use it later in program. The problem is that no operand matches those operands std::string == int. So does that mean that the app sees '-r' as int? I'm a bit confused here.
int main(int argc, char* argv[])
{
std::vector<std::string> argList;
cout<<"argc: "<<argc<<endl;
for(int i=2; i<=argc; i++)
{
argList.push_back(argv[i]);
}
if(argList.at(2) == '-r') cout<<" Good job ";
}
There are several issues with your program:
You iterate i until i == argc, that will attempt to construct a string from argv[argc], a NULL pointer due to the requirement by C and C++ standards that argv[argc] be 0 (NULL), see this SO question. argv is an array with argc pointers to null-terminated character strings (terminated by ASCII NUL, 0), the array itself is terminated with a NULL pointer (not counted in argc). Now, in C++ you can construct a string from a pointer to a null-terminated character string, but passing a NULL pointer to a string constructor results in undefined behavior, see this SO question, also see the list of std::string constructors here, you are implicitly using constructor (4) in that list (from c-string).
You start pushing onto argList with i==2, which means argList[0] will contain argv[2], you then reference argList.at(2), which would correspond to argv[4], this is not likely what you meant.
String literals use double quotes
I've corrected these and created a working program, click here
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
vector<string> argList;
cout << "argc: " << argc << endl;
for(int i=0; i < argc; ++i)
{
argList.push_back(argv[i]);
}
cout << "Program name is " << argList[0] << endl;
if(argc > 1) {
if(argList.at(1) == "-r") {
cout << " Good job, you supplied -r\n";
} else {
cout << "Unrecognized option " << argList[1]
<< "\nUsage: " << argList[0] << " -r\n";
}
}
return 0;
}
The problem is your use of single quotes in '-r'. You want double quotes here:
if(argList.at(2) == "-r") cout<<" Good job ";
The reason is that in C++, single quotes are used for characters only. There is such a thing as a "multi-byte character constant", which is what '-r' ends up being. This is something completely different from a string constant, which is what you want.
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
so i need to read in a file, then create a word count and a character count for each time the character appears using an array. each word ends with whitespace, comma, period, etc. also i need to put a tolower and an equation to set the letters to the right array with an x-'a' function or something like that.
list of errors from puTTy(crappy program i know but it's required)
project8.cpp: In function âint main()â:
project8.cpp:17: error: âfile1â was not declared in this scope
project8.cpp:18: error: expected â;â before âwhileâ
project8.cpp:36: error: expected â}â at end of input
#include <iostream>
#include <string>
using namespace std;
int in_word = false;
int word_count = 0;
char ch;
char low_case;
int char_count[26];
int i;
int main()
{
for (i=0; i<26; i++)
char_count[i]=0;
cin.get(file1.txt)
while('\n' !=(ch=cin.get(file1.txt)))
{
if (' ' == ch || '\n' == ch || '\t' == ch)
in_word = false;
else if (in_word == false)
{
in_word=true;
word_count++;
}
else low_case=tolower(ch);
char_count[int(low_case)-int('a')]++;
}
cout << file1.txt;
cout << words << " words" << endl;
for (i=0; i<26; i++)
if(count[i] !=0)
cout << count[i] << " " << char(i+'a') << endl;
}
The first problem is that you haven't declared file1. It is somewhat unclear what file1.txt really is meant to be: The way it is written, it seems to be an object of type with a member called, txt of type char* or char[N] (with a constant N). From the looks of it, you actually wanted to open a file named file1.txt. This would look like so:
std::ifstream in("file1.txt");
After that you would, of course, use in instead of std::cin to read from the file. For example you could use
for (char c; in.get(c); ) {
// ...
}
to read each individual character of the file and process it appropriately.
Let's play compiler!
You cannot name a variable file1.txt, call it file1
Also, you forgot the semi-colon ; at the end of the line, so
cin.get(file1.txt)
should be
cin.get(file1);
I don't quite know where you are defining this variable, so you may be missing a declaration like
const char* file1="file1.txt";
Furthermore, you start trying to access some variable count after your for-loop here:
count[i]
Did you mean to use char_count?