Why does this code give no output on online C++ compilers? [duplicate] - c++

This question already has answers here:
String plus Char - what is happening?
(5 answers)
C++. Why std::cout << char + int prints int value?
(2 answers)
cout and String concatenation
(3 answers)
How object cout prints multiple arguments?
(4 answers)
Closed 10 months ago.
I was experimenting with a statement in C++ using online compilers. When I try to run this specific code
cout << num[i] + " " + num[i];
The online compilers give no output. I can change the + symbol to << but I want to know the reason that the code does not give any output on these online compilers.
Online compilers that I tried are onlinegdb, programiz, and jdoodle.
#include <iostream>
#include <string>
int main() {
std::string num = "123";
int i = 0;
std::cout << num[i] + " " + num[i];
return 0;
}

C++ is not like JavaScript or many higher-level languages, as in you may not delimit you data with +'s or ,'s. As shown in Lewis' answer, each item you wish to have printed must be separated by an insertion delimiter (<<). As for extracting, you may use the extraction delimiter (>>).
In your case, you are doing mathematical operations on the the characters themselves (adding together their numerical ASCII representations together, which could print unprintable and invisible characters). The printable ASCII characters range from 32 (space character) to 127 (delete character) (base 10). When summing '1' + ' ' + '1' you are left with (49 + 32 + 49) or (130) which exceeds the printable character range. Or you may also be accessing garbage as #pm100 said in the comments due to pointer arithmetic.
Here is an example of using the insertion operator:
#include <iostream>
int main(void) {
int some_int = 1;
std::cout << "this is my " << some_int << "st answer on StackOverflow :)"
<< std::endl;
return 0;
}
And as for the extraction operator:
#include <iostream>
int main(void) {
int num;
std::cout << "Enter an integer: ";
std::cin >> num; // stores the input into the `num` variable
std::cout << "The number is: " << num << std::endl;
return 0;
}
Pointer arithmetic:
const char* get_filename(const char* _path, size_t _offset) {
return (_path + _offset);
}
// This is an example
//
// path = "path/to/my/file/file.txt";
// offset ^ ^
// 0 |
// + 16 ------------|
// path = "file.txt";

Related

wstring decreasing by one character every time it is printed c++ [duplicate]

When i try to add text to string i get random values.
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "333" + 4;
}
I get some random text like:↑←#
"333" is a const char [4] not std::string as you might expect(which by the way still doesn't have operator+ for int). Adding 4, you're converting it to const char * and then moving the pointer by 4 * sizeof(char) bytes, making it point to memory with garbage in it.
It happens because those are two different types and the adding operator does not work as you may expect.
If you intend to concatenate the string literals "333" with the int value of 4 than you should simply use count like:
cout << "333" << 4; // outputs: 3334
If you want to display the sum, than use string to int conversion with the stoi() function.
cout << stoi("333") + 4; // outputs: 337
Note: When using stoi(): If the string also contains literals, than the conversion will take the integer value from the beginning of the string or will raise an error in case the string begins with literals:
cout << stoi("333ab3") + 4; // same as 333 + 4, ignoring the rest, starting a
cout << stoi("aa333aa3") + 4; // raise error as "aa" can't be casted to int
As you want to add text to text, solution would be to use proper types:
cout << std::string( "333" ) + "4";
or for c++14 or later:
using namespace std::string_literals;
cout << "333"s + "4"s;
I honestly do not know what you are trying to achieve by adding int to string. In case you want to add 333+4, you need to Parse string in to int like this :
edit:Typo
#include
using namespace std;
int main()
{
cout << std::stoi("333") + 4;
}

How to know how many digits are in a numeral in C++ [duplicate]

This question already has answers here:
C++ - how to find the length of an integer
(18 answers)
How to count amount of digits in a given number in c++
(3 answers)
Closed 1 year ago.
I have a C++ code that asks for a number to work with. I want to use the loop for with the length of this number, such as what we are used to do in JavaScript using .length property.
For example:
the input is: 2563
int input;
for (i = 0; i < input.length; i++)
It is supposed to repeat 4 times.
How could I do it?
If you always receive the number via some text input (command line or a text file) then there's no reason to do modulo arithmetic. If your loop is even tightly coupled to the number of symbols received, it makes even less sense to operate on the integer. Instead, receive the input as a string.
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a positive integer: ";
std::getline(std::cin, input);
for (int i = 0; i < input.length(); i++) {
std::cout << "Digit number " << i << " is " << input[i] << std::endl;
}
}
NOTE input[i] is a character, and any arithmetic operations on that character will not work the same way you expect it to on the integer's individual digits. If you want the number to work with numerically (instead of just symbolically) you can convert to an integer using the std::stoi family of functions ("string to integer").
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a positive integer: ";
std::getline(std::cin, input);
for (int i = 0; i < input.length(); i++) {
std::cout << "Digit number " << i << " is " << input[i] << std::endl;
}
int value = std::stoi(input);
std::cout << "The number times 2 is " << value * 2 << std::endl;
}
NOTE The std::stoi family of functions provide error checking functionality. My above example omits that for simplicity, and because this sounds like a school assignment where input validation is the user's problem.

Problem with comparison between pointer and integer C++

I've been getting error messages saying
[Error] ISO C++ forbids comparison between pointer and integer [-fpermissive]
and don't know how to fix it.
I've searched stackoverflow for people with same issues, but only came up with this: c++ compile error: ISO C++ forbids comparison between pointer and integer which didn't answer my question. What also confused me is that the error is on line indicated by the HERE comment, which is the if statement, but I don't see any integers in the condition part.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int main() {
char in[100];
gets(in);
int len = strlen(in);
std::string s(in);
int count = 0;
for (int i = 0; i < len; i++) {
if (s.at(i) == " ") { // <-- HERE
count += 1;
}
}
cout << count;
}
Say the input is Hello World, I am expecting output to be 1, but I didn't get any output.
The expression " " is a string literal with type const char [2].
The expression s.at(i) returns a char&.
So, s.at(i) == " " is trying to find an equality operator taking
char& on the left and a reference to the literal array const char(&)[4] on the right.
It finds one or more candidates for operator==, but the argument types don't match any exactly, so next it tries the implicit conversion sequences - this is where the char& undergoes integral promotion to int, and the array decays to const char*.
It still doesn't find a match with these, and gives up, but that explains why it has int and const char * arguments when the error is emitted.
All that is a long way of saying that you write character literals like ' ' in C++. They're not just a string of length 1 as in some other languages (and you can't write strings with single quotes at all).
Change the if statement
if (s.at(i) == ' ') {
count += 1;
}
since s.at(i) returns char&, " " is a string, and ' ' is a char.
The problem is that " " is a string literal not a character! A character literal would be ' '.
The error is a bit misleading, because " " is acutally a const char*.
C++ differentiates between character strings and single characters in the literals by different quoting symbols (" vs '). The " " in your code is the string literal that contains one space, a single space character would be written as ' '. The function std::string::at returns a single character.
A small example will show you how the compiler looks on that
#include <iostream>
#include <string>
#include <typeinfo> // for typeid
using namespace std;
int main() {
string s = "Hello, world!";
cout << typeid(" ").name() << endl;
cout << typeid(' ').name() << endl;
cout << typeid(s.at(0)).name() << endl;
return 0;
}
see online demo of above code.
But, to be precise, identical types aren't required for comparisons in C++, but the types need to be compatible. Pointers (string literals are considered constant pointers to characters, in fact pointing to the first character in the literal) and integers (to which char is promoted in your case) are not compatible. To "fix" your problem quickly, change s.at(i) == " " to s.at(i) == ' ', but your program will remain problematic: it still contains a lot of C code that's problematic in it self, too. A possible C++ version could be this:
#include <iostream>
#include <string>
using namespace std;
int main() {
int count = 0;
string line;
std::getline(cin, line);
for (const auto c: line) {
if (c == ' ') {
count++;
}
}
cout << "Your input \""<< line << "\" contains " << count << " space(s)." << endl;
return 0;
}

atoi() Not Working with std::string::substr()

This is a snippet of my code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h> // atoi()
int main() {
std::string line;
std::ifstream numbers("numbertest.txt");
if (numbers.is_open()) {
while (std::getline(numbers, line)) {
for (int i = 0; i < line.length() - 4; i++) {
for (int n = 0; n < 5; n++) {
std::cout << atoi((line.substr(i, 5)[n]).c_str());
}
I want to operate with numbers in groups of 5, from a file. Why is atoi() not working here? It says "expression must have class type" under the second parentheses on the atoi line.
line.substr(i, 5) creates a temporary std::string containing 5 characters in line from position i
std::string foo = "hello world";
int i = 2;
std::cout << foo.substr(2, 5) << '\n';
would print "llo wo".
The [n] operator returns the nth character of the substring, which is of type char, you are then calling .c_str() on that character rather than on the substring.
You can avoid the .c_str() entirely by using std::stoi, e.g.
std::cout << "line.substr(i, 5) = " << line.substr(i, 5) << '\n';
std::cout << std::stoi(line.substr(i, 5));
aoti and stoi both take a string representation of a number as their input and return the numeric value. For example:
std::string input = "123a";
// std::cout << input * 10 << '\n'; // illegal: input is a string, not a number.
int i = std::stoi(input); // converts to integer representation, i.e. 123
std::cout << i * 10 << '\n'; // outputs 1230
----- EDIT -----
You're actually asking all the wrong questions. What you want to do is take an input pattern and output all of the patterns of 5 characters in it.
Example input: "1020304050"
Example output: 10203 02030 20304 03040 30405 04050
You don't need to convert these to numbers to output them, you can just output the characters. The problem with your original code wasn't the conversion it was the incorrect sequence of operators.
std::substring is expensive, it has to create a new, temporary string, copy characters from the original into it, and then return it, and it does it for every call.
The following should achieve what you're trying to do:
while (std::getline(numbers, line)) {
for (size_t i = 0; i < line.length() - 4; i++) {
for (size_t n = 0; n < 5; n++) {
std::cout << line[i + n];
}
std::cout << '\n';
}
}
If you really want to invoke substr, you could also implement this as
while (std::getline(numbers, line)) {
for (size_t i = 0; i < line.length() - 4; i++) {
std::cout << line.substr(i, 5) << '\n';
}
}
Here's a working demonstration: http://ideone.com/mXv2z5
Try atoi( line.substr(i,5).c_str() )
Or if you want for each character
std::cout << ((line.substr(i, 5)[n]) - '0');
Or even better
std::cout << (line[i+n]) - '0');
Note that: atoi is not ascii to integer. It converts a ctype string to number. For a single character, this conversion should be done using arithmetic or lookup table.
Also there is no point converting characters to integer and then print it (back to chacters). You should better print digit character itself.
Moreover in C++, I would prefer to use stringstream instead or atoi. On C++11 there are even more advanced solutions like sto*.

Can't output hex in C++ [duplicate]

This question already has answers here:
C++ cout hex format
(3 answers)
Closed 9 years ago.
I'm trying to output a hex value assigned to a variable x and I can't seem to get it working in C++. I can do it in standard C but am getting undesired results in C++.
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, const char * argv[])
{
unsigned char x = 0xFF;
printf("%X\n", x);
cout << dec << x << endl;
cout << hex << x << endl;
return 0;
}
prints
FF
\377
\377
Because it's unsigned char, the stream thinks you want to output a character, rather than its value. Try casting to int
cout << hex << (int)x << endl;
You might also want to use setw(2) and setfill('0') stream modifiers to pad single-digit hex numbers to 2 digits (similar to using %02X with printf).