Program not coutting - c++

I am using th following code but it only asks me for a input and closes without couting my input
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(){
int balance=0;
int withdraw=0;
char* str;
cin.getline(str,10);
cout<<str;
withdraw=atoi(strtok(str," "));
balance=atoi(strtok(NULL," "));
cout<<withdraw<<" "<<balance;
return 0;
}

char* str;
This only gives you a pointer. That pointer doesn't point anywhere, especially not at some chars that you can write to. When you call cin.getline(str,10), it tries to write to where this pointer is pointing to. That gives you undefined behaviour. An easy fix for this is to make str an array of 10 chars:
char str[10];
However, I recommend that you start using std::string instead and figure out how to do strtok-like operations with a std::string. Hint: look at std::istringstream.

You need to allocate memory for str.
char *str = new char[10];
otherwise using uninitialized pointer will invoke undefined behavior. And call delete to free the allocated memory once you done with str.
delete[] str;
Instead of using char *, it is better to use std::string.

Related

resize std::string without initializing memory

I'm using a C routine to write to an std::string's datafield. This is a contrived example, in reality I'm getting a non-null terminated string and its size via network:
#include <string>
#include <cstdio>
#include <cstring>
const char* str = "Some examplory string..";
int main()
{
std::string some_str;
some_str.resize(strlen(str));
std::strcpy(&some_str.front(), str);
printf(some_str.c_str());
}
Now according to cppref there's no overload for resize() which just resizes and does not initialize memory with '\0' or something else. But why should I pay for that if all I'm doing is overwriting it again? Can this somehow be avoided?

what is wrong with this code and why is it not printing anything

#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int i=0;
string s1 = "";
s1[i++]='F';
s1[i++]='U';
s1[i++]='A';
s1[i++]='A';
s1[i++]='D';
cout << s1;
return 0;
}
You're trying to modify elements in an empty string.
If you want your code to work there are several ways to do this:
add elements to s1, you can use s1 += 'A' or s1.push_back('A') instead.
Allocate enough space to modify each element by doing s1.resize(5) after string s1 = "";.
And possibly more, but that should get you started. Think of std::string as an array of characters. If your array is empty, you either have to resize it or add things to it.
Note: Don't use #include <bits/stdc++.h> just do #include <string>.
Note: Avoid using using namespace std;
s1 is empty, any indexing into it will be out of bounds and lead to undefined behavior. Do e.g. s1 += 'F' instead. – Some programmer dude

Inputting a string into dynamically allocated memory of char in c++

Is this correct or is there a better way to do this.
Visual Studio gives an error saying 'strcpy() is depreciated'.
using namespace std;
char* ptr;
ptr=(char *)calloc(1,sizeof(char));
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
ptr = (char *)realloc(ptr, top + eqn.size()+1);
strcpy(ptr, eqn.c_str());
P.S. I want to ptr to be the exact size of the input equation.
Assuming that what you're trying to achieve is to create a modifiable char buffer given a std::string, the better choice is to use std::vector<char> to create such a buffer.
#include <vector>
#include <string>
#include <iostream>
//...
void foo(char *x)
{
// do something to 'x'
}
using namespace std;
int main()
{
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
// construct vector with string
std::vector<char> ptr(eqn.begin(), eqn.end());
// add null terminator
ptr.push_back(0);
foo( &ptr[0] );
}
The above creates a modifiable, null-terminated C-string by utilizing the std::vector called ptr. Note that there are no calls to malloc, calloc, etc.
strcpy is deprecated because it's a common source of buffer overflow problems, that are generally fixed with strncpy. Having said that, you are much better off using std::string in the first place.
If you want to have a duplicate of a string with malloc, you may simply use strdup:
char* ptr = strdup(eqn.c_str());
// ..
free(ptr);

segmentation fault using c++ copy instead of memcpy

I'm using C++ copy algorithm to copy a string literal, (instead of memcpy) but I'm getting segmentation fault I don't know why though. here is the code:
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[]) {
// if using copy with regular pointers, there
// is no need to get an output iterator, ex:
char* some_string = "this is a long string\n";
size_t some_string_len = strlen(some_string) + 1;
char* str_copy = new char(some_string_len);
copy( some_string, some_string + some_string_len, str_copy);
printf("%s", str_copy);
delete str_copy;
return 0;
}
Fix :
char* str_copy = new char[some_string_len];
^ notice square bracket
Free memory using :
delete [] str_copy;

Function that will act like an Strlen C++

I want to make a function that will do the same as Strlen does, andI get the error: "string subscript out of range". I tried fixing it but has no idea.
heres the code:
#include "stdafx.h"
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int strlen1( string str)
{
int count=0;
int i=0;
while (str[i]!='\0')
{
count++;
i++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
string input;
cin >> input;
cout << strlen1(input) << endl;
return 0;
}
thanks!
In short, for a non-const std::stringaccessing an element beyond the string length has Undefined Behavior (more precisely, when using the non-const operator[] for that).
C++98 §21.3.4/1, about std::string::operator[]:
If pos < size, returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise the behavior is undefined.
And your string is non-const.
You can make it const, which will then invoke a special provision in the standard that guarantees zero result for element n, but that does not address the problem that your function is completely redundant for std::string.
Perhaps you mean to have argument type char const*.
That would make more sense, and then also the function would work.
Cheers & hth.,
You seem to be under the misconception that std::string is the same as a C-style string (char const*). This is simply not true. There is no null terminator.
Here's your strlen function the only way it will work:
int strlen1(string str) { return static_cast<int>(str.size()); }
std::string has a nice size() method for this.
strlen is based on zero terminated strings (char*, or char arrays), C++ string are based on length + data, you can't access to data after the end of string (where a terminal zero would be). Beside that, getting the length is a standard property of C++ strings (size()), hence the standard way of writing strlen is just to call size.