Errors when putting a string variable into system() - c++

I'm having trouble getting system() to run a command in a string variable.
ostringstream convert;
convert << getSeconds(hours);
string seconds = convert.str(); /* converts the output of 'getSeconds()' into
a string and puts it into 'seconds' */
string cmd = "shutdown /s /t " + seconds;
system(cmd);
getSeconds() just takes an int in hours, converts it into seconds and returns an int in seconds. Everything runs fine, no errors, until it reaches system(cmd);. The compiler then spits out this error:
error: cannot convert 'std::string {aka std::basic_string<char>}' to
'const char*' for argument '1' to 'int system(const char*)'
Here are my includes:
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>

I know this has already been answered by comments, but not really explained:
The system function is a C function. It does not "understand" C++ style strings. For that, you will need to use the c_str() function. In other words, you need system(cmd.c_str());.
This applies to a large number of C style functions that are still available in C++, since one of the main features of C++ is that you can still use traditional C-code (for the most part) in C++. So, the same applies to almost any C style function that takes a string - printf("cmd=%s", cmd.c_str()); would print what your command is.
It would be possibe to write your own wrapper function:
int system(const std::string &cmd)
{
return system(cmd.c_str());
}
Now, the rest of your code can use system with a regular C++ style string.

system takes a C string not a std::string, so you must call the c_str function first.
system(cmd.c_str());

Related

Compiling error while using getline(): 'mismatched types'

I keep getting this error (it's a really long one but I think the most important part is this):
main.cpp:9:30: note: mismatched types 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'const char [2]'
While compiling this bit of code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = getline(cin, " ");
return 0;
}
The lines in the error won't match with the ones in the code I brought up here because I don't know how to make a new line whilst writing code in the Stack Overflow editor; I'm new here ;) Anyways, the error points to the line with the declaration of string x.
Basically what I want this code to do is to get a line from the user until he/she hits space. Maybe I'm doing something wrong from the beginning, so I'm open for suggestions of fixing this problem. (I'm not very experienced in C++, it's just that my teacher required to complete a task using this language.) Thanks,
Anthony
The second parameter of std::getline() is a reference to a std::string variable that accepts the read data. The string is not outputted in the function's return value.
Also, std::getline() does not accept a string for the delimiter. It takes only a single character.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string x;
getline(cin, x, ' ');
return 0;
}

C++: cin.getline - no instance of overload function

I'am trying to write a line of text to a .txt file, but visual studio 2015 is giving me the following error.
Severity Code Description Project File Line Suppression State
Error (active) no instance of overloaded function "std::basic_istream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits]" matches the argument list Studying c:\Users\Klaas\Documents\Visual Studio 2015\Projects\Studying\Studying\Studying.cpp 16
and
Severity Code Description Project File Line Suppression State
Error C2664 'std::basic_istream> &std::basic_istream>::getline(_Elem *,std::streamsize,_Elem)': cannot convert argument 1 from 'std::string' to 'char *' Studying1 c:\users\klaas\documents\visual studio 2015\projects\studying1\studying1\studying1.cpp 16
My source code:
#include <iostream>
#include "stdafx.h"
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream myFile;
string myText;
myFile.open("sometext.txt");
cout << "Write text to save to file: ";
cin.ignore();
cin.getline(myText, sizeof(myText));
myFile << myText;
myFile.close();
return 0;
}
I have done multiple searches and found answers such as including
cin.ignore();
above the
cin.getline
, but i just can't get it to work and i don't really understand what the error means, and i don't see why it thinks i'm trying to convert a string to char.
Any tips would be very welcome :)
You are not using correct function. Instead of cin.getline() you should use
std::getline(cin, myText)
cin.getline() expects a pre-allocated char*, and your myText is not. It is also very hard to somehow manage to preallocate a buffer long enough for std::basic_istream::getline(), so this function is almost never useful at all.
use getline(cin,myText) I honestly don't know why this problem exists or if it even is a problem but i know for a fact that this works.
See : http://www.cplusplus.com/reference/istream/istream/getline/
See : http://en.cppreference.com/w/cpp/io/basic_istream/getline
The first parameter of this function getline must be a char *, not a string.
char myText[1024];
cin.getline( myText, sizeof(myText) );
As mentioned everywhere else, it's better to use the std::getlinefunction:
http://en.cppreference.com/w/cpp/string/basic_string/getline

How to convert wchar_t (or wchar_t* or CORBA::WChar*) to string?

In my app I have to use CORBA::WChar* (or equivalent wchar_t*) but my program also needs to save some information to the PostgreSQL database. To insert data to PostgreSQL in C++ I use SOCI. And there's the problem because :
The following types are currently supported for use with into and use expressions:
char (for character values)
short, int, unsigned long, long long, double (for numeric values)
char*, char[], std::string (for string values)
std::tm (for datetime values)
soci::statement (for nested statements and PL/SQL cursors)
soci::blob (for Binary Large OBjects)
soci::row_id (for row identifiers)
so theres no wchar_t* or wstring supported ... and I need to convert CORBA::WChar (or wchar_t or wchar_t*) to string. How to do this?
I also have problem with wide chars (and strings), using CodeBlocks 10.5 :
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
const wchar_t *val = L"ąśżźćłóń";
wcout << val << "\n";
return 0;
}
shows:
E:\Temp\Untitled1.cpp||In function 'int main(int, char**)':|
E:\Temp\Untitled1.cpp|7|error: converting to execution character set: Invalid argument|
||=== Build finished: 1 errors, 0 warnings ===|
how to fix it?
I also need the code to be portable, that I can run it both on unix/linux and windows.
I would suggest boost::locale::conv::utf_to_utf<char>(wchar_t*) that simply convert you wchar_t* string into UTF-8 for more information please read boost::locale documentation
What kind of database doesn't let you store Unicode strings? My suggestion would be to use a decent database.

Chain value of string variable with some text and print it to standard output in C++

I want to do something really simple: I have function that has string parameter and I want to chain it to some constant string, then output result to console like this:
void test(string s){
cout << "Parameter of this function was: " << s;
}
In other languages chaining like this works, but in C++ the compiler is unhappy: error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
You probably forgot to #include <string> or #include <iostream>.
What version of Visual Studio are you using? Your code sample is correct C++ (as long as you have the appropriate "using namespace std;").
Putting similar code through g++ works fine.

Using Strncmp with a string from a file

Goodnight to everyone, I'm trying to parse an .h file so I can have a small console frontend to change its values, but when I try to use strncmp with a string read from a file and a string defined in code to compare with the file string I get a strange error from the compiler that I cant resolve, here is my source code:
//Test to basic file operations
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main (void){
string line;
ifstream myfile("PIDconfig.h");
if(myfile.is_open()){ //if file is open
while(myfile.good()){
getline(myfile, line);
if(strncmp(line, "static float", 12) == 0){
cout << line << endl;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
And the error that I get:
tiago#tiago-laptop:~$ g++ file.cpp
file.cpp: In function ‘int main()’:
file.cpp:17: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int strncmp(const char*, const char*, size_t)’
If some one could help me I would be very glad, I have already searched StackOverflow but I didnt found anyone with the same problem, almost all strncmp problems use arrays to store their strings and as far as I went, no one was having a problem using it and file I/O.
std::string overloads operator==. You can simply compare two std::string object using ==.
Also, your input loop is incorrect.
the problem is that strncmp() function overloaded for strncmp(const char*, const char*, int)
but you want to call it by strncmp(string, string, size_t)
you must convert string to const char* with
c_str()
for example
string str = "Hello";
char * arr = str.c_str().
you get it?
if(strncmp(line.c_str(), "static float", 12) == 0){
should work
The problem is that you're reading data from the file as a C++ string, and the strncmp function works on C style strings. To fix this, you can either extract a raw C style string from the C++ string using .c_str(), or you can use the C++ string's .compare function:
line.compare(0, 12, "static float")