Ofstream, use variable to the name - c++

Hello for all people...
Sorry for my english, but speak spanish...
In this week, study and work for this proyect, I want create a software to make files(.us)...
Example
char name[50]; //Or string
cin>>name;
ofstream PlayerPawn("D:\\UDK\\UDK_XXX\\Development\\Src\\" + name+"\\Classes\\_PlayerPawn.us");
But the compiler has error in the Operator binary plus
Any alternative, examples or something for create the file in specific directory
Good bye and Thx!

Either side of operator+ must be a std::string1 for operator+ to concatenate strings:
string name;
cin >> name;
ofstream PlayerPawn("D:\\UDK\\UDK_XXX\\Development\\Src\\" + name + "\\Classes\\_PlayerPawn.us");
And use std::string for this stuff; with std::string there's no danger of buffer overflows that you get with char*.
1 Actually it just needs to be a class type that supports operator+, not specifically std::string, but then you have no idea what it will do.

I believe you want name to be a std::string - otherwise, name + [suffix] will try to add the suffix string to the array and will not compile. If you really want to keep the name as an array, you should use strcat to append the strings together.

Related

What's the necessity of string in c++ while we already have char[]?

Many topics have discussed the difference between string and char[]. However, they are not clear to me to understand why we need to bring string in c++? Any insight is welcome, thanks!
char[] is C style. It is not object oriented, it forces you as the programmer to deal with implementation details (such as '\0' terminator) and rewrite standard code for handling strings every time over and over.
char[] is just an array of bytes, which can be used to store a string, but it is not a string in any meaningful way.
std::string is a class that properly represents a string and handles all string operations.
It lets you create objects and keep your code fully OOP (if that is what you want).
More importantly, it takes care of memory management for you.
Consider this simple piece of code:
// extract to string
#include <iostream>
#include <string>
main ()
{
std::string name;
std::cout << "Please, enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "!\n";
return 0;
}
How would you write the same thing using char[]?
Assume you can not know in advance how long the name would be!
Same goes for string concatenation and other operations.
With real string represented as std::string you combine two strings with a simple += operator. One line.
If you are using char[] however, you need to do the following:
Calculate the size of the combined string + terminator character.
Allocate memory for the new combined string.
Use strncpy to copy first string to new array.
Use strncat to append second string to first string in new array.
Plus, you need to remember not to use the unsafe strcpy and strcat and to free the memory once you are done with the new string.
std::string saves you all that hassle and the many bugs you can introduce while writing it.
As noted by MSalters in a comment, strings can grow. This is, in my opinion, the strongest reason to have them in C++.
For example, the following code has a bug which may cause it to crash, or worse, to appear to work correctly:
char message[] = "Hello";
strcat(message, "World");
The same idea with std::string behaves correctly:
std::string message{"Hello"};
message += "World";
Additional benefits of std::string:
You can send it to functions by value, while char[] can only be sent by reference; this point looks rather insignificant, but it enables powerful code like std::vector<std::string> (a list of strings which you can add to)
std::string stores its length, so any operation which needs the length is more efficient
std::string works similarly to all other C++ containers (vector, etc) so if you are already familiar with containers, std::string is easy to use
std::string has overloaded comparison operators, so it's easy to use with std::map, std::sort, etc.
String class is no more than an amelioration of the char[] variable.
With strings you can achieve the same goals than the use of a char[] variable, but you won't have to matter about little tricks of char[] like pointers, segmentation faults...
This is a more convenient way to build strings, but you don't really see the "undergrounds" of the language, like how to implement concatenation or length functions...
Here is the documentation of the std::string class in C++ : C++ string documentation

String as function and called by other sub class with integer value

I want to create a file with C++ and write something in it. I have two classes, one with a Vererbung::writer(string name) and another subclass called Vererbung1(int zahl). Without the integer it works peferctly but when I want to write the integer to string and paste it after the function it wont work.
this works normally
Vererbung.cpp
void Vererbung::Writer(string name)
{
ofstream text;
text.open ("test.txt", ios::trunc);
text <<"write something\n";
text <<"again2 \n";
text <<"again 3\n";
text << name;
text.close();
}
Vererbung1.cpp
include "Vererbung.h"
void Vererbung1::Writer(int zahl)
{
std::ostringstream ostr;
ostr<< zahl;
name = "\n" "Test\n""Test\n""Test\n" ostr.str();
Vererbung::Writer(name);
}
When I run it in main it says that I need a ';' before ostr.str(); how can I fix this, If I want a integer value to string in a file in it?
This problem is very unclearly stated but, if we assume that name is an std::string, then:
name = "\n" "Test\n""Test\n""Test\n" ostr.str();
This is just a bunch of string literals written next to each other, followed by an std::string expression also just randomly floating there in free space.
Your computer doesn't know what you want it to do.
Although you actually can concatenate string literals in this way (literals are something like "hello world", but not something like aStringVariable), that doesn't apply to arbitrary expressions (and you don't even need it where you've used it).
I think that what you meant was this:
name = "\nTest\nTest\nTest\n" + ostr.str();
I hope that your C++ book teaches this; if not, get a better one.

How to divide the input taken from user in two parts and assign them to two different arrays in C++?

If we take the input from user by asking them, like below:
cout << "Enter your course code and course name: ";
Now if the user enters CS201 Introduction to Programming, how can I only assign the code part, i.e. CS201 to an array, let's say;
char courseCode[10];
And how can I assign the name part in the array, let's say:
char courseName[50];
I want to do this to 5 students, using the structure defined below:
struct student
{
char courseName[50];
char courseCode[10];
};
student stu[5];
It's actually kind of simple once you remember that the input operator >> stops on white-space, and also know about the std::getline function.
Then you can do something like
std::string courseCode;
std::string courseName;
std::cin >> courseCode;
std::getline(std::cin, courseName);
Note that I use std::string for the strings instead of arrays. This is what you really should use. If you're not allowed (by your teacher or something) and must use arrays, then you can't use std::getline but instead have to use std::istream::getline instead.
Store the input in a single string say x
Now on x perform linear search for the first whitespace and split the string about the first whitespace. Store the two resultant strings in your struct.
I solved my problem using the cin.getline() functions to get the string in token pointer and then used strchr(char [], cahr) of <string> header file to separate the current string from the place where the first white space comes. Then I copied both separated strings into my desired elements of my structure using strcpy() function.

Tokenizer - Initialization with '{...}' expected for aggregate object

I'm working on creating a program that will take a fraction and reduce it to it's lowest terms. I'm using a tokenizer to parse through the string (In my case I'm reading in a string) and separate the numerator from the denominator.
I'm getting the following error, and am looking for an explanation to why it's happening. I've looked up people with similar problems, but I'm still a beginner looking for a basic explanation and suggestion for an alternative way to solve it.
RationalNum() // Default
:numerator(0), denominator(1){}
RationalNum(int num) // Whole Number
:numerator(num), denominator(1){}
RationalNum(int num, int denom) // Fractional Number
:numerator(num), denominator(denom){}
RationalNum(string s)
{
int num = 0;
char str[] = s;
}
I know the problem lies in the setting the char array to s.
Thanks for taking the time to look at this.
You are trying to initialise an array of char to a std::string, which is an object. The literal meaning of the error is that the compiler is expecting an initialisation that looks something like this :
char str[] = {'1','2','3','4'};
However, since you are planning on string manipulation anyway, you would have a much easier time just keeping the string object rather than trying to assign it to a char array.
Instead of building your parser from scratch, you can use string stream and getline. with '/' as your delimiter. You can initialise an std::stringstream with a string by passing it as an argument when constructing it. You can also use another stringstream to convert a string into a number by using the >> operator.

how can i add this variable to my path for ifstream?

I'm trying to append my path and contain a variable as part of the path but I'm getting an error.
What's wrong with it?
fstream fin("E:\\Games\\maps\\" + this->MapNumber + ".map", ios::in|ios::binary|ios::ate);
this->MapNumber is a USHORT
error: 13 IntelliSense: expression must have integral or unscoped enum type
In C++ you can't use + to concatenate literal strings. You can use + with std::strings to concatenate them, but that won't work with integer or other types. You need to use a stream instead. Insertion and extraction into a stream will cause the types that support it to represent themselves as text, but you probably already knew this from general I/O.
Try with something like this:
std::stringstream filename;
filename << "E:\\Games\\maps\\" << this->MapNumber << ".map";
std::fstream fin(filename.str().c_str(), ios::in|ios::binary|ios::ate);
Just like with everything else, to use something you need to include the header that declares it first. In order to use std::stringstream you need to include <sstream>.
You can't use operator+ on a string and another type like string or so you can either:
Option1: turn all variables into strings to append them
string s = string("E:\\Games\\maps\\") + string(itoa(this->MapNumber)) + string(".map");
option2: use stringstream as #k-ballo explained
option3: use the good old C fprintf (my personal favourite)
char str[100];
fprintf(str, "E:\\Games\\maps\\ %d .map", this->MapNumber);