Strings

Hello there, I started learning c++ a couple of months ago not everyday and everyhour of my day but I do my best. Anyways uhm in an old language I used to program with using a program called PAWNO, there was a diff way of dealing with strings that I would like to know its equal in c++, here is it:

1
2
new str[128];
format(str, sizeof(str),"%s has set you to level %d. ",Name,level);



I tried something like

1
2
 char x[50];
 x = "HI";


I know it's a wrong format and I cannot assign an array like that but I was just trying out my luck but I am desperate to know if there is an equal to what I asked for.
Last edited on
You can do it this way

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
#include <string>
using namespace std;

int main() {

string greeting="Hi";
for (int i =0; i < greeting.size(); i++)
	{cout  << greeting[i];}
return 0;
}


To use char you have to assign h to x[0] and i to x[1]

1
2
x[0]=H;
x[1]=I;

Last edited on
What's the point of looping? doesn't it work the same if you just cout << greeting; ?
Last edited on
Mimicking the style of the OP, two alternatives. The C version using snprintf is very similar.

The C++ version uses a stringstream instead. The string str is created simply to mimic the style of the OP, it isn't really required.

Of course, if you just want to output the resulting text, there's no need for any of these intermediate stages, just use std::cout instead of oss.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

int main()
{
    /* C language version */
    {
        const char * Name = "Fred";
        int level = 7;
        
        char str[128];
        snprintf(str, sizeof(str),  "%s has set you to level %d. ", Name, level);
    
        puts(str);
    }
    

    // C++ language version
    {
        std::string  Name = "Fred";
        int level = 7;
        
        std::ostringstream oss;
        oss << Name  << " has set you to level " << level << ". ";
    
        std::string str = oss.str(); // temporary string, not really needed.
        
        std::cout << str << '\n';
    }
}
But how big is the std::string ? since in the C version you specified the size to be 128
But how big is the std::string ?

It will automatically resize so that it is exactly as large as necessary.

If you want to check the size, it can be found using the member function size().
 
std::cout << "Size of string is " << str.size() << '\n';


This is one of the advantages of C++ strings, they are usually safer than C-strings because they automatically adjust as required.

http://www.cplusplus.com/reference/string/string/size/
Topic archived. No new replies allowed.