C++ copy char to string - c++

int main()
{
string sample = "abcdef";
string result;
result[0]='a';
cout<<result[0];
}
I am trying to copy a char into a string result;
the output should be a displayed. but there is no display.and no error message.
direct copy is working // result=sample;
how is this code wrong?

A few issues with your code:
(not a bug) Try not to use using namespace std;
result is initially empty so assigning to a specific character position will actually be a bug. If you append to it with the += operator then it works as expected.
It should not be an issue but the std::cout buffer might not be flushed on some particular occasions. You can force to flush with std::cout.flush().
Always end with a newline for clarity
#include <iostream>
int main()
{
std::string sample = "abcdef";
std::string result;
result +='a';
std::cout << result << std::endl;
}
Produces:
Program returned: 0
Program stdout
a
Godbolt: https://godbolt.org/z/ocvGP6333

This should result in run time error while accessing
result[0]
hence you should use
result+="a";
Also, you are not using sample variable in your code, if you intend to copy the first char from sample to result, you can use
int main() {
string sample = "abcdef";
string result;
result+=sample[0];
cout<<result[0];
}

Related

How can i store hex value in string and get the value and size of the string

I am trying to store a hex value in a string and latter retrieve it after some time, but while retrieving No value is coming size of the string is also coming 0. Sample code:
using namespace std;
int main() {
std::string s;
s.assign("\x00\x53"); // std::string s ="\x00\x53"
cout<<s.size();
}
output is coming 0
Try using \\ instead of \:
s.assign("\\x00\\x53");
Now you have:
#include <iostream>
using namespace std;
int main() {
std::string s;
s.assign("\\x00\\x53"); // std::string s ="\x00\x53"
cout << s.size() << endl;
cout << s << endl;
}
Output:
8
\x00\x53
From C++14 onwards, we have the option of using string literals, using that feature you can do this:
std::string s1 = "\x00\x53"s;
This will do what you expect and will return the correct value for size().
If you cannot use C++14 features, you need to use a string constructor that will allow you to specify the length of the string. You can do this:
std::string s1( "\x00\x53", 2);
You can see demo for both versions here.

Error: C++ literal memory mishandling

I have tried a lot to debug my code but it is still not working.The whole code just crashes but there is no allover error I am presenting the code please try to debug that one.
Code:
#include <iostream>
#include<conio.h>
#include<string.h>
#include<fstream>
using namespace std;
void write(char fname[],char text[])
{
strcat(fname,".txt");
ofstream w(fname,ios::app);
w<<text;
w<<"\n";
w.flush();
w.close();
cout<<" sippy "<<fname<<" ";
}
int main ()
{
int login=0;
char t[100],id[100]="Its id ",pass[100]="Its password";
login=1;
strcpy(t,id);
strcat(t,"\n");
strcat(t,pass);
cout<<" finally ";
write("database",t);
getch();
strcpy(t,id);
getch();
cout<<t<<" showing t here";
getch();
cout<<" hope this works for now ";
getch();
cout<<"\nEnter the text"<<endl;
write(id,t);
}
The above mentioned code does not work on tdm gcc code blocks
Edit 1:
Ok so now the major problem has been detected it is a minor bug usually caused because of drawback of a bad programming style. As it is often suggested that if a string is passed to a function then that particular function allocates a new string at the memory of the passed string. Since the passed string is a literal the code editing the newly formed string would try to edit a read only literal memory which is an error
Literals are read only because if compiler finds the use of same literal at some different place then it would be able to use same memory to flash the contents of literal therefore it becomes a necessity to make a literal read only and use of c-style string carefully(rather std::string should be used)
Thanks to all
If you are facing a SegFault I think this line could be the problem :
write("database",t);
because in your write function you use strcat on fname but you pass a read-only string.
Also, I think it might be best to use real c++ instead of c+ like :
#include <string>
#include <iostream>
#include <fstream>
void my_write(std::sting & fname, std::string & text) {
std::string file = fname + ".txt";
std::osftream w(file, std::ios::app);
w << text << "\n";
w.flush();
w.close();
}
int main() {
std::string t = "";
std::string id = "Its id";
std::string pass = "Its password";
std::string fname = "database";
int login = 1;
t = id + "\n" + pass;
my_write( fname, t);
}
I haven't test it but the idea is here.

Program not printing out string from text file c++

I am trying to read a certain line from a text file using a function for later use, but it does not seem to be returning a string. Function below:
std::vector<std::string> TextArray(string filePath) {
int arrayNum = 0;
std::vector<std::string> stringArray;
ifstream file (filePath);
std::string str;
while (std::getline(file,str)){
stringArray.push_back(str);
}
return stringArray;//returns an array
}
Inside main:
std::vector<std::string> fileString = TextArray("c:/computerAi/saved");
std::cout << fileString[1] << std::endl;
I get an error saying "Vector subscript out of range"
I suspect that the path may be the problem. "c:/computerAi/saved" is not a valid path. It should be "C:\\computerAi\\saved". The double backslashes are necessary because backslash is the escape character in C/C++. If the file stream failed to open, then the vector might be empty. Also, I'm assuming here that C:\computerAi\saved is actually a file and not a directory.
Also, as bvj mentioned in a comment, subscript 1 is the second element in the vector, not the first. So, if you were wanting the first element, try fileString[0] instead of fileString[1].
Edit: I still suspect that the path is the problem. The following program works for me:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
std::vector<std::string> TextArray(std::string filePath)
{
int arrayNum = 0;
std::vector<std::string> stringArray;
std::ifstream file(filePath.c_str());
std::string str;
while (std::getline(file,str))
{
stringArray.push_back(str);
}
return stringArray;//returns an array
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<std::string> fileString = TextArray("c:\\temp\\testing.txt");
std::cout << fileString[1] << std::endl;
return 0;
}
When I tried this program with an invalid path (a file that did not exist,) I got the exact behavior described by the question. When I tried it with a valid path, it returned the second line of the input file, exactly as expected.

Different values on the function implementation

I'm kind of new with programming and I have wired problem.
I tried to search and read about it, but without success.
I have main file and one class (on windows)
main:
main()
{
LogOut x();
x.WriteToDelayFile(1.2, 3);
}
LogOut class:
void LogOut::WriteToDelayFile(double simTime, int nodeNum)
{
string fileName = "Delay" + nodeNum;
FILE* pFile = OpenFile(fileName);
fputs ("something\n",pFile);
}
I can't figure it out but when I call to WriteToDelayFile(2, 3) with values, I get garbage values edit: (for example, on debug- nodeNum=321546 instead of nodeNum=3) on the LogOut::WriteToDelayFile(double simTime, int nodeNum) implementation
Why does it happen?
Thanks.
As user657267 pointed out in his comment, you may not concatenate a string literal and an int string fileName = "Delay" + nodeNum;. Here you are getting a pointer into the literal, that may even be out of range:
string s = "hello"+1; // leads to "ello" in s
The probably intended concatenation can be done using a stringstream:
#include <sstream>
#include <assert>
void concat_check()
{
std::stringstream ss;
ss << "hello" << 1;
assert(ss.str() == "hello1");
}
Wolf you are a little bit wrong
string s = "hello"+3;
gives "lo" in s data
and
string si = string("hello")+3;
is incorrect you need to use stringstream instead
std::stringstream ss;
ss << "hello" << 3;
std::string s = ss.str();
Dudi Reuveni how can you tell that nodeNum has wrong data?

converting integer to string C++

I am trying to convert an integer to char array and I came across this piece of code
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
But when I try to print the value of s it still prints 5. I don't know if its supposed to do that or am I doing something wrong? Besides I would prefer if I could convert the same int to char array. But I would appreciate any help in the matter.
Thanks!
Code taken from: Alternative to itoa() for converting integer to string C++?
Yes, it's supposed to do that. You'd (primarily) notice the difference from just printing a number out directly if you do some other string-type manipulation on the result (e.g., concatenating it with other strings, searching for characters in the string).
Just for example:
std::cout << i+i; // should print "10"
std::cout << s+s; // should print "55"
Besides I would prefer if I could convert the same int to char array.
char *charPtr = new char[ s.length() + 1 ] ; // s is the string in the snippet posted
strcpy( charPtr, s.c_str() ) ;
// .......
delete[] charPtr ; // Should do this, else memory leak.
If you would like to stop worrying about issues like that you might be interested in boost/lexical_cast.hpp.
#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>
int main() {
const int i=5;
const char* s = boost::lexical_cast<std::string>(i).c_str();
std::cout << s << std::endl;
}