I made this function to convert a string to an integer (school assignment) and my function is not seeming to work, if it picks up any non-numeric data it should return INT_MAX. It's not returning any data no matter what, and seemingly not returning to main either.
#include <iostream>
#include <climits>
#include <string>
using namespace std;
int stringToInt(string input){
int i = 0;
if(input[i] == '-'){
i++;
//First while loop controls valid input
while(input[i] != '\0'){
if(input[i] < 49 || input [i] > 47){///Can't figure this out
return INT_MAX;
}
i++;
}
}
//Now to calculate result
int result = 0;
i = 0;
if (input[i] == '-'){
i++;
while (input[i] != '\0'){
result = (input[i] - 49) + (result * 10);
i++;
}
result = result * (-1);
return result;
}
else{
while (input[i] != '\0'){
result = (input[i] - 49) + (result * 10);
i++;
}
return result;
}
}
//////MAIN////////
int main(){
string number;
int actualNumber;
int answer;
cout << "This is my main function. Enter a string to evaluate" << endl;
getline(cin, number);
actualNumber = stringToInt(number);
cout << actualNumber;
cout << endl;
return 0;
}
Your 2nd and 3rd while loops don't increment i so you end up looping on the same number forever and never get to '\0'.
ie this one
while (input[i] != '\0'){
result = (input[i] - 48) + (result * 10);
}
i never changes.
Related
Hi is there way to check that your code is Recursion or not in c++? I write code but someone tell me that it isn't Recursion. I want to make sure.
#include <iostream>
#include <conio.h>
using namespace std;
bool winding(string str, int len) {
int counttrue = 0;
for(int i = 0; i < len; i++){
if(str[i] == '1') counttrue++;
else if(i != len - 1 && str[i] == '0' && str[i + 1] == '0') {
counttrue += 2; i++;
}
}
return (counttrue == len);
}
int main() {
string strwinding;
cin >> strwinding;
cout << winding(strwinding, strwinding.length()) << endl;
cout << "Continue...";
getch();
return 0;
}
A recursive function calls itself, and yours doesn't, so it's not recursive.
Assuming that the definition of a "winding" string is
The empty string, or
A 1 followed by a "winding" string, or
00 followed by a "winding" string,
a straightforward translation could look like this:
bool winding(const string& str, int index)
{
return index >= str.size()
|| ((str[index] == '1') && winding(str, index+1))
|| ((index < str.size() - 1)
&& str[index] == '0'
&& str[index+1] == '0'
&& winding(str, index+2));
}
// ...
cout << winding(strwinding, 0) << endl;
A recursive function is a function that calls itself, like for instance:
int fac(int x)
{
if (x <= 1) return 1; else return x * fac(x - 1);
}
You can easily check if a function is recursive if you create a breakpoint at the beginning of the function and see if this breakpoint is reached more than once if you call the function from outside once.
Our teacher gave us this exercise:
"Given a string like '-5,14' write a function that returns the float value of -5,14
I used double here just to test the precision, but it also didn't work with floats.
[also i'm from Europe, we use the comma instead of the dot. Oh also we aren't allowed to use the type string and bool, we have to "make" them like in C]
This is what i came up with, and it seems to work a little bit. Positive numbers are similar, but wrong, and given a negative number, the result is similar to 10 times the positive of the given number.
It should work like this:
I read the string into an array of characters;
I check if the first character is a minus. if so, subtract 1 from the number of integer figures because i will count them later starting from index 0;
I count the number of integer figures with a loop from the start of the array to the ',' character;
I count the number of decimal figures with a loop from after the ',' to the end of the string;
[Keep in mind for the next step that, following the ASCII table, the code for the character of a number is that number + 48]
I add to the result variable every integer figure multiplied by ten to the power of whatever place in the number it has.
I do the same for the deicmal values but with the negative exponent.
if the number was negative, i multiply the result with -1.
But for some reason it's not working properly. The lower the number is, the less accurate it is (given 4,5 the result is 9, but given 345,543 the result is 350,43)
#include <iostream>
#define EOS '\0'
#define DIM 100
#define TRUE 1
#define FALSE 0
void leggiN(char* c)
{
std::cout << "Insert a number: ";
std::cin >> c;
}
double stof(char* str)
{
double Result = 0;
double ascii_to_int = 48;
int i = 0;
int j = 0;
int IntegerDigits = 0;
int DecimalDigits = 0;
int CommaIndex;
int isNegative = FALSE;
if (str[0] == '-')
{
IntegerDigits = -1;
isNegative = TRUE;
}
while (str[i] != ',')
{
++IntegerDigits;
++i;
}
CommaIndex = i;
++i;
while (str[i] != EOS)
{
++DecimalDigits;
++i;
}
for (i = (CommaIndex - 1); i >= 0; --i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, j));
++j;
}
j = 0;
for (i = (CommaIndex + 1); str[i] != EOS; ++i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, -j));
++j;
}
if (isNegative == 1)
Result = Result * -1;
return Result;
}
int main()
{
char str[DIM];
leggiN(str);
std::cout << stof(str);
}
use j = 1 to start your second for loop. You are trying to raise 10 to the power of -0
j = 1;
for (i = (CommaIndex + 1); str[i] != EOS; ++i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, -j));
++j;
}
If your code return 9.0 when you enter "4,5", your problem has nothing to do with imprecision.
There are other problems in your code, I've tried to un it and got a SEGFAULT...
#include <iostream>
#define EOS '\0' // 0 being such a special value, there is no need to
// define a named constant for it.
#define DIM 100
#define TRUE 1 // the language defines boolean values, avoid defining
#define FALSE 0 // unnecessary named constants for something that already
// exists.
void leggiN(char* c)
{
std::cout << "Insert a number: ";
std::cin >> c; // Inserting from cin to a char* is a BIG no-no.
// some compilers won't even allow it, for good reasons
// i.e.: what is the length of the array pointed to?
}
double stof(char* str) // you are indicating that you may modify str?
{
double Result = 0;
double ascii_to_int = 48; // this is a terrible name.
int i = 0;
int j = 0;
int IntegerDigits = 0;
int DecimalDigits = 0;
int CommaIndex;
int isNegative = FALSE;
if (str[0] == '-') // is str a valid pointer? what happens if NULL ??
{
IntegerDigits = -1;
isNegative = TRUE;
// you fail to skip the sing character, should have ++i here.
}
while (str[i] != ',') // what happens if there is no ',' in the string?
{ // you should check for str[i] == 0.
++IntegerDigits;
++i;
}
CommaIndex = i;
++i;
while (str[i] != EOS)
{
++DecimalDigits; // why do you count decimal digits?
++i; // you do not use this result anyway...
}
for (i = (CommaIndex - 1); i >= 0; --i)
{
// what happens if you have non-digit characters? they participate
// in the conversion??
// you call std::pow(), but do not include <cmath> at the top of the file.
// isn't str[i] - '0' clearer ?
Result += (str[i] - ascii_to_int) * (std::pow(10, j));
++j;
}
j = 0;
for (i = (CommaIndex + 1); str[i] != EOS; ++i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, -j));
++j;
}
if (isNegative == 1) // you had defined constants fot this, but don't use them.
Result = Result * -1;
return Result;
}
int main()
{
char str[DIM];
leggiN(str);
std::cout << stof(str);
}
Here is one way to achieve what you want.
#include <iostream>
#include <string>
const char DECIMAL_POINT = ','; // we'll use a named constant here....
// usually, we'd have to check the locale
// for regional specific information.
// works like atod(), conversion stops at end of string of first illegal character.
double stof(const char* str) {
// check input, must be not null, not empty
if (!str || str[0] == 0)
return 0;
int i = 0;
bool isNegative = false;
// take care of leading sign
if (str[0] == '-' || str[0] == '+') {
isNegative = (str[0] == '-');
++i;
}
// convert integer part.
double result = 0;
while ('0' <= str[i] && str[i] <= '9') {
result = (result * 10) + (str[i] - '0');
++i;
}
// only do decimals if they are there.
if (str[i] != DECIMAL_POINT)
return (isNegative) ? -result : result;
++i; // skip decimal point
double decimals = 0;
double multiplier = .1;
while ('0' <= str[i] && str[i] <= '9') {
decimals += (str[i] - '0') * multiplier;
++i;
multiplier *= .1;
}
result += decimals;
return (isNegative) ? -result : result;
}
int main() {
// always use std::string to read strings from cin.
std::string str;
std::cout << "Insert a number: ";
std::cin >> str;
std::cout << "in: " << str << " out: " << stof(str.c_str()) << '\n';
return 0;
}
I am writing code where a user will enter a roman numeral and the output will be a regular number. I have accomplished this, however I'm having trouble with the next part, which is to:
Extend the program so that it reads and converts all input numbers until end of file on standard input. You'll probably be able to do this simply by adding an appropriate "reading loop" around the code that reads a single line.
My current code is:
#include<iostream>
#include<string>
using namespace std;
int value(char r){
if(std::toupper(r) == 'I')
return 1;
if (std::toupper(r) == 'V')
return 5;
if (std::toupper(r) == 'X')
return 10;
if (std::toupper(r) == 'L')
return 50;
if (std::toupper(r) == 'C')
return 100;
if (std::toupper(r) == 'D')
return 500;
if (std::toupper(r) == 'M')
return 1000;
return -1;
}
int romantoArabic(string &str){
int res = 0;
for (int i=0; i<str.length(); i++)
{
int s1 = value(str[i]);
if (i+1 < str.length())
{
int s2 = value(str[i+1]);
if (s1 >= s2)
{
res = res + s1;
}
else
{
res = res + s2 - s1;
i++; // Value of current symbol is
}
}
else
{
res = res + s1;
i++;
}
}
return res;
}
int main(){
string str;
cout<<"";
cin>>str;
cout << ""<< romantoArabic(str) << endl;
return 0;
}
Say, for example, the user was to enter the following (BTW, this is what needs to be entered, and at the moment my code does not allow me to do):
i
ii
iii
iv
v
vi
vii
viii
ix
My output is:
1
When it should be:
1
2
3
4
5
6
7
8
9
while (cin >> str) {
cout << ""<< romantoArabic(str) << endl;
}
I'm trying to write a function which only reads four ints out of a users input like this: ewzge242jfdsiii23 So it is supposed to save only 2422.
This is my code and it just gives me some weird output, if I let it cout number.
Can you maybe see my mistakes and explain why I can't do it how I did and what I could do instead? Thanks a lot!
int readnumber ( ) {
char kar, ont_kar, ont_ont_kar;
int number;
while (kar != '\n' ){
cin.get (kar);
if (kar >= '0' && kar <= '9') {
old_kar=kar;
old_kar = old_kar*10 + (kar - '0');
old_old_kar = old_kar ;
} //if
} //while
if (old_kar < 9999) {
number=old_kar;
}//if
else {
number=old_old_kar;
}//else
}//readnumber
This looks too complicated, why do you need so many variables?
Also old_kar and old_old_kar are misstyped. The function does not return, that should be the main problem.
Here's a quick simple example:
unsigned readnumber(int number_of_chars) {
char ch;
unsigned number = 0;
while (number_of_chars > 0) {
std::cin.get(ch);
if ('\n' == ch)
break; // Stop on new line
if (ch < '0' or ch > '9')
continue; // Skip non-digits
--number_of_chars; // One digit processed
number = number * 10 + ch - '0'; // And added to the result
}
return number;
}
And here is a full version without break or continue:
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
using namespace std;
int readnumber(int number_of_chars) {
char ch;
int number = 0;
while (number_of_chars > 0) {
std::cin.get(ch);
if ('\n' == ch)
return number;
if (ch >= '0' and ch <= '9') {
--number_of_chars;
number = number * 10 + ch - '0';
}
}
return number;
}
int main() {
int n = readnumber(4);
cout << "You entered: " << n << endl;
return 0;
}
NB: Always compile with all warnings on, this will save you a lot of time.
there is a function which I have written it myself for large numbers' Add (+) operator in C++, now I'm trying to convert it to C language but there is some problems with strings :( I tried so many things but it seems it is not working, Here is a piece of my code in C++:
#include <iostream>
#include <stdlib.h>
using namespace std;
string num1,num2,Result;
string AddF (string num1, string num2)
{
string Result;
char d;
int sum,f=0,Len1=num1.length(),Len2=num2.length();
while(Len1>=0 || Len2>=0)
{
sum=0;Len1--;Len2--;
if (Len1>=0)
sum+=num1[Len1]-'0';
if (Len2>=0)
sum+=num2[Len2]-'0';
d=((sum+f)%10)+'0';
Result=d+string(Result);
f=(sum+f)/10;
}
d=f+'0';
if (f!=0)
Result=d+string(Result);
if(Result[0]=='0')
Result.erase(0,1);
return Result;
}
int main()
{
cout << "Please Enter 1th Number: "; cin >> num1;
cout << "Please Enter 2th Number: "; cin >> num2;
Result=AddF(num1,num2);
}
Now My Converted Code in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *num1,*num2,*Result;
char* AddF (char *num1, char *num2)
{
char *Result,*d;
int sum,f=0,Len1=strlen(num1),Len2=strlen(num2),Temp;
while(Len1>=0 || Len2>=0)
{
sum=0;Len1--;Len2--;
if (Len1>=0)
sum+=num1[Len1]-'0';
if (Len2>=0)
sum+=num2[Len2]-'0';
Temp=((sum+f)%10);
itoa(Temp,d,10);
strcat(d,Result);
Result=d;
f=(sum+f)/10;
}
itoa(f,d,10);
if (f!=0)
{
strcat(d,Result);
Result=d;
}
if(Result[0]=='0')
memmove(&Result[0], &Result[0 + 1], strlen(Result) - 0);
return Result;
}
int main()
{
printf ("Please Enter 1th Number: "); scanf ("%s",&num1);
printf ("Please Enter 2th Number: "); scanf ("%s",&num2);
Result=AddF(num1,num2);
}
It will Crash when It reach last line.
Your code doesn't work because of several reasongs
You have to allocate d. I would recomend you declare d as an array and use the snptrinf or _snprintf functions something like
char d[32];
int x = 3;
snprintf(d, sizeof(d), "%d", x);
You have to pass an allocated memory buffer to scanf too, you can pass an array, something like
char num1[32];
char num2[32];
scanf("%31s", num1);
scanf("%31s", num2);
and the same goes for Result
You are returning an array instead of a pointer from the AddF() function, you can use a temporary array and then copy the string at the end, and return the copy, don't solve the problem using global variables.
You are assigning to Result unecessarily, if you use strcat() the destination string will be always appendend to the end of the source string.
And this will in fact be a mistake, since you declared Result as a pointer, and you are making point somewhere else, thus loosing the reference to the original pointer.
This might be what you want
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *AddF (char *number0, char *number1)
{
char *result;
int sum;
int carry;
int lengths[2];
int count;
if ((number0 == NULL) || (number1 == NULL))
return NULL;
lengths[0] = strlen(number0);
lengths[1] = strlen(number1);
result = malloc(lengths[0] + lengths[1] + 1);
if (result == NULL)
return NULL;
carry = 0;
count = 0;
while (lengths[0] >= 0 || lengths[1] >= 0)
{
lengths[0]--;
lengths[1]--;
sum = 0;
if (lengths[0] >= 0)
sum += number0[lengths[0]] - '0';
if (lengths[1] >= 0)
sum += number1[lengths[1]] - '0';
memmove(result + 1, result, ++count);
result[0] = ((sum + carry) % 10) + '0';
carry = (sum + carry) / 10;
}
result[count] = '\0';
if (result[0] == '0')
memmove(result, result + 1, count);
if (carry == 0)
return result;
memmove(result + 1, result, ++count);
result[0] = carry + '0';
result[count] = '\0';
return result;
}
int main()
{
char *numbers[2] = {NULL, NULL};
char *result;
size_t i;
for (i = 0 ; i < sizeof(numbers) / sizeof(*numbers) ; i++)
{
char chr;
size_t length;
length = 0;
printf ("Please Enter %ldth Number: ", 1 + i);
while ((chr = getchar()) != '\n')
{
char *number;
number = realloc(numbers[i], (2 + length));
if (number == NULL)
{
if (numbers[0] != NULL)
free(numbers[0]);
if (numbers[1] != NULL)
free(numbers[1]);
return -1;
}
number[length] = chr;
numbers[i] = number;
length += 1;
}
numbers[i][length] = '\0';
}
result = AddF(numbers[0], numbers[1]);
if (result != NULL)
{
printf("%s\n", result);
free(result);
}
if (numbers[0] != NULL)
free(numbers[0]);
if (numbers[1] != NULL)
free(numbers[1]);
return 0;
}