I'm trying to make a function which takes QString as well as an int.
Convert QString variable into a filename for ofstream, then take the integer and place it into the file. So far I have managed to take a constant filename such as "Filename.dat" and write a variable into it. However when I try to use QString like this :
void write(const char what,int a){
std::ofstream writefile;
writefile.open("bin\\" + what);
writefile << a;
writefile.close();
}
I get an error
void write(const char,int)': cannot convert argument 1 from 'const char [5]' to 'const char
This is the function which calls write();
void Server::on_dial_valueChanged(int value)
{
write("dial.dat",value);
}
When I use "bin\dial.dat" instead of combining "bin\" with a string it works fine. ofstream.open(); uses "const char*".
I've tried all the filetypes so they may not match my description
The question is-
Does anybody have an idea how to combine "bin\" and a QString and make it work with ofstream?
I've spend a lot of time googling it but still can't make it work.
Thanks!
Any suggestions are more than welcome
void write(const char what,int a) is wrong as you pass only one char to function you should have void write(const char* what,int a) to pass pointer to cstring beginning.
You also want to concat two cstrings and in c++ you can't do it like in other languages but you can use std::string to do what you want.
Try this
#include <string>
void write(const char* what,int a){
std::ofstream writefile;
std::string fileName("bin\\");
fileName+=what;
writefile.open(fileName.c_str());
writefile << a;
writefile.close();
}
Related
I have opened a file to write to, and according to some conditions sometimes I want to print output to the screen and sometimes to the file. So I edited my function to be like this:
Cacl(const std::string &str, const ofstream &to=std::cout)
But I'm getting an error, what may cause this?
no viable conversion from 'std::__1::ostream' (aka 'basic_ostream<char>') to 'const std::__1::ofstream' (aka 'const basic_ofstream<char>')
void Calculator::solve(const std::string &command, const ofstream &to=std::cout) {
std::cout is an object of type std::ostream which is a base class of std::ofstream (it's more general than std::ofstream), so you could just do:
void Calculator::solve(const std::string &str, std::ostream &to = std::cout) {
// instead of ofstream ^^^^^^^
and now you can pass an ofstream object to this function as well.
Also, the ostream shouldn't be const otherwise you won't be able to write to it.
I would like to be able to do the following:
std::cout << str_manip("string to manipulate");
as well as
std::string str;
str_manip(str);
std::cout << str;
For this, I have two functions
#include <string>
// copying
std::string str_manip(std::string str)
{
// manipulate str
return str;
}
// in-place
void str_manip(std::string& str)
{
// manipulate str
}
but they produce the following error:
error: call of overloaded 'str_manip(std::__cxx11::string&)' is ambiguous
How can I overcome this?
The problem is with this call:
std::string str;
str_manip(str);
std::cout << str;
The compiler doesn't know which version of str_manip to call.
You can change your functions to look like this:
#include <string>
// copying
std::string str_manip(const std::string& str)
{
std::string dup = str;
// manipulate dup
return dup;
}
// in-place
void str_manip(std::string& str)
{
// manipulate str
}
Now, the compiler knows that the ambiguous call has to be the function that takes the non-const parameter. You can also be sure that your call that returns a std::string to the << operator isn't modifying your string.
This might be not the thing you are looking for, but for your code
std::cout << str_manip("string to manipulate");
the parameter to str_manip is not a string but const char* (actually an array, but convertible to a char pointer). You can overload based on that.
std::string str_manip(const char* s)
{
std::string str(s); // create str
// manipulate str
return str;
}
However, let's look at the big picture. When you see str_manip in your code, does this mean "change the string" or "make a new string based on the given string"? Do you want to be intentionally ambivalent on the real meaning?
Consider yourself reading your code in 1 year in future. What will you think when you see a call to str_manip - does this mutate its parameter? Does the answer to the previous question depend on context?
The goal in writing code is to make it clear, especially in a multi-paradigm language like C++. So, in my opinion, just don't do overloading that you are thinking about. Instead, make 2 distinct names, like
void frobnicate_str(std::string&) {...}
std::string get_frobnicated_str(std::string) {...}
I have following overloaded function
void testFun(QByteArray& arr){
QTextStream out(stdout);
out << "QByte" << endl;
}
void testFun(QString str){
QTextStream out(stdout);
out << "QStr" << endl;
}
Why function void testFun(QString str) is called if I use const QByteArray as argument.
It means - this block of code:
QByteArray bA("aaa");
const QByteArray bB(bA);
testFun(bA);
testFun(bB);
gives following output:
QByte
QStr
Since the first overload takes a non-const QByteArray, it does not get used.
C++ has a feature called Converting Constructors. This means that a single-argument constructor that is not marked as explicit can be used automatically to convert one type into another for function overload resolution.
QString has such a constructor that takes a const QByteArray&. Therefore, when selecting what function overload to use, the compiler can first convert the QByteArray to a QString using that constructor, and then proceed to pass that QString into your second function.
Please see http://en.cppreference.com/w/cpp/language/overload_resolution for more information.
The underlying cause is that Qt (and by extension: you!) allows writing non-typesafe code: there's an implicit conversion from QByteArray to QString. Define QT_RESTRICTED_CAST_FROM_ASCII project-wide, wipe the build folder and rebuild the project. The call that uses the const object won't compile then, and you'll have to fix the function signatures: you should have been taking const references all along.
void testFun(const QByteArray &arr){
QTextStream out(stdout);
out << "QByte" << endl;
}
void testFun(const QString &str) {
QTextStream out(stdout);
out << "QStr" << endl;
}
Is there a way to do something like this :
void test(char *userInput){
//code
}
char userInput = "test";
test(userInput);
I have the error : Process finished with exit code 139 so how can i proceed ?
Is there a way to do something like this :
Sure, just change your code a bit:
void test(const char *userInput){
//code
}
int main() {
const char* userInput = "test";
test(userInput);
}
I have the error : Process finished with exit code 139 so how can i proceed?
I'm pretty sure the compiler did show you some further errors before this one came up. Fix these first.
You marked this as a C++ question ... std::strings are very easy to use.
// NOTE: userinput can be either std::string OR const char*
void test(std::string userinput)
{
// code, perhaps echo testing input
std::cout << userinput << std::endl;
}
// test 290 - invoked somewhere in main
int t290(void)
{
std::string userInput = "test1";
test(userInput);
// some times you can save some typing
test("test2"); // function declared as above
// accepts both const char* or std::string
return (0);
}
As other people pointed out, there's an error in your code, char should be changed to const char*. Char only holds one value, not the entire string, and if your function takes a const value the string has also to be. Also, given you're using C++, you can use std::string wich is really straightforward to use.
I am very new to C++ and still trying to learn syntax and best practices.
I've defined a method with a single parameter:
void foo(const std::string& name)
1) Is this a proper parameter declaration for a function that will be taking in a string defined by the user in, for example, a main method?
2) If this is proper/recommended syntax, what would an instantiation of a sample parameter look like?
Yes, that is the correct syntax. You can call it and provide parameters several different ways:
With a string literal:
foo("bar");
With a string variable:
std::string b = "bar";
foo(b);
With the result of a function return type string:
std::string quux();
foo(quux());
With a char* variable:
int main(int argc, char const* argv[]) {
foo(argv[0]);
}
I'm not sure if I fully understand your question, but I'll try to clarify it.
You use the terminology 'method'. I'm assuming that your method is encapsulated in a class? If so, then :-
In your header file (eg. source.h),
class dog
{
...
public:
void foo(const std::string &name);
...
};
In your source file (eg. source.cpp)
void dog::foo(const std::string &name)
{
// Do something with 'name' in here
std::string temp = name + " is OK!";
}
In your 'main' function, you can instantiate your 'dog' class, and call the 'foo' function like :-
void blah()
{
dog my_class;
my_class.foo("Testing my class");
}
If you want a function (ie. a 'method' that is not encapsulated within a class), then what you have is correct.
In your source file (eg. source.cpp)
void foo(const std::string &name)
{
// Do something with 'name' in here
std::string temp = name + " is OK!";
}
If you want to be able to call your function from outside that particular source file, you'll also need to forward declare your function in a header file.
In your header file (eg. source.h)
void foo(const std::string &name);
To call your function,
void blah()
{
foo("Testing my class");
}
Hope this helps!
1)
It is a proper parameter declaration if function foo() doesn't mean to change the string. The 'const' keyword is used to signify that the string won't be changed by the receiver.
If you write code in foo() which modifies the string you will get compiler error/warning.
2)
std::string theString = "Hello";
foo( theString );
Is this a proper parameter declaration for a function that will be taking in a string defined by the user in, for example, a main method?
Yes.
#include <string>
using namespace std;
void foo(const string& name)
1) Yes, that's a very good way to do it if you only need to read the string in the function.
2) There is no instantiation going on?
1) For most functions, it would be a fine signature. However, since you mentioned main(), there are only two valid signatures:
int main()
int main(int argc, const char* argv[])
...as you can see, you have to use C-style strings due to C-legacy compatibility (and efficiency)
2) Not sure I understand your second question, but since std::string has a constructor that takes a const char*, you can just say:
foo("hello");
or:
std::string input;
std::cout << "Enter some text: ";
std::cin >> input;
foo(input);