Cannot convert a character/string to int - c++

When I run my code I get this error at compile time:
# g++ -std=c++0x sixteen.cpp -O3 -Wall -g3 -o sixteen
sixteen.cpp: In function ‘int main()’:
sixteen.cpp:10: error: call of overloaded ‘stoi(char&)’ is ambiguous
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2565: note: candidates are: int std::stoi(const std::string&, size_t*, int) <near match>
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2626: note: int std::stoi(const std::wstring&, size_t*, int) <near match>
I looked up that error and followed the instructions that other questions on here have done, however I still get that error after removing using namespace std;. Why is this still happening and what can I do to get rid of it?
Code:
#include <iostream>
#include <string>
int main() {
std::string test = "Hello, world!";
std::string one = "123";
std::cout << "The 3rd index of the string is: " << test[3] << std::endl;
int num = std::stoi(one[2]);
printf( "The 3rd number is: %d\n", num );
return 0;
}

std::stoi takes a std::string as its argument, but one[2] is a char.
The easiest way to fix this is to use the fact that the digit characters are guaranteed to have contiguous values, so you can do:
int num = one[2] - '0';
Alternatively, you can extract the digit as a substring:
int num = std::stoi(one.substr(2,1));
And another alternative, you can construct a std::string using the constructor that takes a char and the number of times that char should appear:
int num = std::stoi(std::string(1, one[2]));

Related

comparison of integer expressions of different signedness: correct way of using "for" loop when handling string type

below is c++ code. And I am getting these warnings when compile
comparison of integer expressions of different signedness: ‘int’ and ‘std::__cxx11::basic_string::size_type’ {aka ‘long unsigned int’} [-Werror=sign-compare]
15 | for(int x=0; x<s.length();x++)
~^~~~~~~~~~~
different signedness means that I am comparing long unsigned int which is 64 bits to int (which should be 32 bit) I did not know.. that string.length returns that type. So my question is how to write these simple instructions in c++ without any error showing when compiled with -Wall -Werror
I also get following error message. I supposed string class is in namespace std so the question is: when do we get this error and what that error tells. I think its saying that my program uses only namespace which is std so its not required to do std:string s to create a variable . this removes the error string s without namespace. is this correct thinking or is there any other meaning too
f.cpp:7:1: error: label ‘std’ defined but not used [-Werror=unused-label]
7 | std:string s="hello";
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string s="hello";
char c[s.length()-1];
s[1]='b';
char d='x';
s.push_back(d);
s+='x';
strcpy(c,s.c_str());
for(int x=0; x<s.length();x++)
{
cout<<c[x];
}
}
Because str.length() returns long unsigned int rather than int, casting it as an int should prevent it from giving an warning or error.
Instead of
std::string str = "Test";
for (int i = 0; i < str.length(); i++) {
something(str[i]);
}
Try
std::string str = "Test";
for (int i = 0; i < (int) str.length(); i++) {
something(str[i]);
}

Compile errors when calling GNU Octave from C++

I'm trying to write a function that embeds the Octave interpreter in C++, as described here https://octave.org/doc/v4.0.1/Standalone-Programs.html .
I'm trying to do this from a program that I'm writing in Eclipse, and trying to compile with GCC on Linux. I want to be able to call an external script, as in the second example in the link.
My code so far looks like this.....
#include <iostream>
#include <oct.h>
#include <octave.h>
#include <parse.h>
#include <interpreter.h>
using namespace std;
class OctaveInt {
public:
void callOctave (double, int, string);
OctaveInt(string path );
private:
octave::interpreter interpreter;
};
// Member functions including constructor..
OctaveInt::OctaveInt(string path)
{
// Constructor - initialises engine and sets path
int status = interpreter.execute();
octave_value_list p;
p(0) = path;
octave_value_list o1 = octave::feval ("addpath", p);
}
void OctaveInt::callOctave(double params, int size, string name) {
std::cout << "Hello World" << std::endl;
int n = 2;
octave_value_list in;
octave_value_list p;
for (octave_idx_type i=0; i < size; i++)
in(i) = octave_value(params[i]);
octave_value_list out = octave::feval (name, in);
std::cout << "Output is ";
std::cout << out(0).int_value();
}
int main() {
double params[] = {100, 2, 3, 4, 5, 6};
int size = 6;
string path = "/home/arwel/eclipseWorkspace_new/octaveCaller/src/";
OctaveInt octI(path);
octI.callOctave(params, size, "myFunction");
return 0;
}
When I try to compile however, I get a series of errors.....
Invoking: GCC C++ Compiler
g++ -std=c++0x -I/usr/include/octave-5.2.0/octave/ -I/usr/share/octave/5.2.0/etc/tests -I/usr/lib/x86_64-redhat-linux6E -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/octaveCaller.d" -MT"src/octaveCaller.o" -o "src/octaveCaller.o" "../src/octaveCaller.cpp"
../src/octaveCaller.cpp: In constructor ‘OctaveInt::OctaveInt(std::string)’:
../src/octaveCaller.cpp:31:6: warning: unused variable ‘status’ [-Wunused-variable]
int status = interpreter.execute();
^
../src/octaveCaller.cpp: In member function ‘void OctaveInt::callOctave(double, int, std::string)’:
../src/octaveCaller.cpp:48:32: error: invalid types ‘double[octave_idx_type {aka long int}]’ for array subscript
in(i) = octave_value(params[i]);
^
../src/octaveCaller.cpp:42:6: warning: unused variable ‘n’ [-Wunused-variable]
int n = 2;
^
../src/octaveCaller.cpp: In function ‘int main()’:
../src/octaveCaller.cpp:65:44: error: no matching function for call to ‘OctaveInt::callOctave(double [6], int&, const char [11])’
octI.callOctave(params, size, "myFunction");
^
../src/octaveCaller.cpp:65:44: note: candidate is:
../src/octaveCaller.cpp:38:6: note: void OctaveInt::callOctave(double, int, std::string)
void OctaveInt::callOctave(double params, int size, string name) {
^
../src/octaveCaller.cpp:38:6: note: no known conversion for argument 1 from ‘double [6]’ to ‘double’
make: *** [src/octaveCaller.o] Error 1
"make all" terminated with exit code 2. Build might be incomplete.
12:41:36 Build Failed. 3 errors, 2 warnings. (took 1s.927ms)
So it looks like I have some problems with types of variables (??).
I don't really know much C++, so I'm undoubtedly doing some basic C++ mistake. Can someone give me a hand to figure out what I'm doing wrong?

Long, nearly incoherent errors C++

Sometimes I get incredibly long errors in my code that I don't understand so I just rework my code to avoid whatever was causing the error. I had another one today that I simply can't avoid.
My code:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
void readFile(string);
class info {
public:
int rows;
int cols;
vector < string > data;
};
int main(int argc, char **argv){
string filename1;
filename = argv[1];
readFile(filename);
return 0;
}
//should read onle line at a time from a file and print it
void readFile(string filename1){
fstream datafile;
datafile.open(filename1);
while (!datafile.eof()){
string line;
getline(datafile,line);
cout<<line<<endl;
}
datafile.close();
}
The error stems from trying to get the name of the file from argv[1]. It was working fine when I just gave it the file name.
The error:
project2.cpp: In function ‘int main(int, char**)’:
project2.cpp:22:2: error: ‘filename’ was not declared in this scope
filename = argv[1];
^
project2.cpp: In function ‘void readFile(std::string)’:
project2.cpp:32:25: error: no matching function for call to ‘std::basic_fstream<char>::open(std::string&)’
datafile.open(filename1);
^
project2.cpp:32:25: note: candidate is:
In file included from project2.cpp:2:0:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/include/c++/fstream:889:7: note: void std::basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
open(const char* __s,
^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/include/c++/fstream:889:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
I am using Cygwin. I used it last semester as well when I was writing code in C, and my professor had us check certain installation options at the time. Could these installation options be the root of the problem? Or are errors like this common in C++? Thanks.
Just read the error:
project2.cpp: In function ‘int main(int, char**)’: project2.cpp:22:2:
error: ‘filename’ was not declared in this scope filename = argv[1];
^
Here it says that filename is not declared. i.e. You have to declare it or something wrong with the declaration
Looking at the code you have
string filename1;
One assumes you meant
string filename;
Fix this error - then try again
The first error:change filename1 to filename
The second error: you should set a open()functions in the class info.then you can use it

Converting char to int in C++

I'm trying to convert a character from a c string to an int but I keep running into an error.
Here's my code
while(std::getline(file, line)){
if(std::isdigit(line[0]) && std::isspace(line[1]) && std::isdigit(line[2])){
SequenceArray.push_back(line);
if(std::stoi(line[2])== (SequenceArray.size() -1)){
std::cout<< "Success" << std::endl;
The error that I keep getting is as follows:
a1.cpp: In function ‘int main(int, char**)’:
a1.cpp:30:25: error: call of overloaded ‘stoi(char&)’ is ambiguous
if(std::stoi(line[2])== (SequenceArray.size() -1)){
^
a1.cpp:30:25: note: candidates are:
In file included from /usr/include/c++/4.8/string:52:0,
from /usr/include/c++/4.8/bits/locale_classes.h:40,
from /usr/include/c++/4.8/bits/ios_base.h:41,
from /usr/include/c++/4.8/ios:42,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from a1.cpp:1:
/usr/include/c++/4.8/bits/basic_string.h:2823:3: note: int std::stoi(const string&, std::size_t*, int) <near match>
stoi(const string& __str, size_t* __idx = 0, int __base = 10)
^
/usr/include/c++/4.8/bits/basic_string.h:2823:3: note: no known conversion for argument 1 from ‘char’ to ‘const string& {aka const std::basic_string<char>&}’
/usr/include/c++/4.8/bits/basic_string.h:2926:3: note: int std::stoi(const wstring&, std::size_t*, int) <near match>
stoi(const wstring& __str, size_t* __idx = 0, int __base = 10)
^
/usr/include/c++/4.8/bits/basic_string.h:2926:3: note: no known conversion for argument 1 from ‘char’ to ‘const wstring& {aka const std::basic_string<wchar_t>&}’
a1.cpp:35:6: warning: label ‘std’ defined but not used [-Wunused-label]
std:exit(EXIT_FAILURE);
A char implicit converts to a int, you don't need to use extra functions.
'a' = 97, 'b' = 98, 'c'=99, etc., following the ASCII table
So if you write,
char a_char = 'a';
int a_val = a_char;
cout << a_val << endl;
you have:
97
For std::stoi missing, try #include <string> (and enable C++11). However see also this thread - the Windows ports of g++ have had a long-standing issue with support of stoi and to_string.
The second error is that std:exit should be std::exit.
The third error is because of line[2].c_str(). You have not told us what line is but the error message suggests it is a std::string. So line[2] is a char and char does not have any member functions. If you explain what you are trying to do in the code std::atoi(line[2].c_str()) someone will be able to help. Maybe you meant line[2] - '0' which will give an integer between 0 and 9 if the third character in the line was a digit.
std::stoi() is C++11. Not all compilers enable C++11 by default.
The first error is because you haven't enabled C++11 support. GCC currently chooses C++03 by default, and stoi didn't exist in that version.
Add -std=c++11 to the compiler's arguments. If that doesn't work, try -std=c++0x, and think about getting a more up-to-date compiler. If you're stuck with an ancient compiler, then use atoi as in the code you originally posted (or perhaps something involving strtol, if you want to detect errors).
Also make sure you've included <string> for the declaration of that function.
The second error is because you wrote : instead of ::.

Compilation error while using to_string in c++ program

To get precision and scale of a number i am using this simple program. But while converting number into string it is giving compilation error.
g++ precision.cpp
precision.cpp: In function ‘int main()’:
precision.cpp:6: error: ‘to_string’ was not declared in this scope
When I compile with the -std=c++0x switch I get
g++ precision.cpp -std=c++0x
precision.cpp: In function ‘int main()’:
precision.cpp:6: error: call of overloaded ‘to_string(int)’ is ambiguous
/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/basic_string.h:2604: note: candidates are: std::string std::to_string(long long int)
/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/basic_string.h:2610: note: std::string std::to_string(long long unsigned int)
/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/basic_string.h:2616: note: std::string std::to_string(long double)
The source code looks like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string value = to_string(static_cast<int>(1234));
int precision = value.length();
int scale = value.length()-value.find('.')-1;
cout << precision << " " << scale;
return 0;
}
What is causing this error?
The first error is because std::to_string is a C++11 feature, and GCC by default compiles in C++03 mode.
The second error, when you are using the correct flag, is probably because the support for C++11 in GCC 4.4 (which you seem to be using) is quite minimal. As you can see by the error messages, the compiler shows you the alternatives it have.
By the way, you don't need to cast integer literals to int, they are of type int by default. You might want to cast it to long double though, as that's one of the valid overloads and you seems to want to find the decimal point (the code will not work as expected if there is no decimal point in the string, like when converting an integer).
I recommend to use boost::lexical_cast instead.