This is probably a very quick fix, but I'm having trouble figuring out why I'm getting an error.
Code:
#include <iostream>
#include <queue>
#include <vector>
#include <iomanip>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(int argc, char *argv[]){
srand ( time(NULL) );
double randomNumber = (double)(rand() % 100) / 100;
string numCars;
cout << "\nPlease enter the number of cars going through the intersection:" << endl;
cout << "->";
getline (cin, numCars);
for(double i=0; i<numCars; i++){
cout << randomNumber << endl;
}
}
The error is:
traffic.cpp:80: error: no match for ‘operator<’ in ‘i < numCars’
numCars is a string. It should have integer type (char, short, int, long)
You can't compare a string to a numeric value. Read the user input into an unsigned int. Change your code to:
unsigned int numCars;
if( !(cin >> numCars) ) {
// invalid user input, handle it
}
for( unsigned int i = 0 ; i < numCars; ++i ) {
// ...
}
I also changed the data type of i from double to unsigned int. There's no reason to use a floating point number unless somehow a fractional number of cars can pass through that intersection.
you can't compare string with integer or you have to define operator for this. Should numCars be integer?
Related
Hello I am attempting to write a function that will generate a random string of lowercase letters. The length of the random string will be the number the user entered. I have this much so far but i believe i am over complicating things
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
char randString(){
int number;
str::string Str; //str has not been declared error
for(unsigned int i = 0; i <8; i++){
Str += randString(); //str was not declared in this scope error
}
cout << Str << endl; // str was not declared in this scope error
}
int main() {
char c;
int number;
srand (time(0));
cout << "Enter a number.\n"
"That number will generate a random string of lower case letters the length of the number" << endl;
cin >> number;
for (int i=0; i < number; i++){
number = rand() % 26;
c = 'a' + number;
cout << randString();
}
return 0;
}
You changed the value of the variable number inside your for loop, which is also your loop condition variable. This will cause an undefined behavior since the value of number will be changed every time the statement number = rand() % 26; is executed. However, from what I understood reading your problem statement, I think this is what you are trying to achieve:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int number;
char c;
srand(time(NULL));
cout << "Enter a number.\n"
"That number will generate a random string of lower case letters the length of the number" << endl;
cin >> number;
for(int i=0;i<number;i++)
{
c = 'a' + rand()%26;
cout << c;
}
return 0;
}
Hope this helps. Good luck!
Is there any way to get the length of int variable e.g In string we get the length by simply writing int size = string.length();
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i = 0;
cout<<"Please Enter the value of i"<<endl;
cin>>i;
//if user enter 123
//then size be 3 .
// Is it possible to find that size
}
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
int main () {
assert(int(log10(9)) + 1 == 1);
assert(int(log10(99)) + 1 == 2);
assert(int(log10(123)) + 1 == 3);
assert(int(log10(999)) + 1 == 3);
return 0;}
You have a few options here:
(This answer assumes you mean number of printable characters in the integer input)
Read the input as a string and get its length before converting to an int. Note that this code avoids error handling for brevity.
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
cout << "Please enter the value of i" << endl;
string stringIn = "";
cin >> stringIn;
cout << "stringIn = " << stringIn << endl;
size_t length = stringIn.length();
cout << "input length = " << length << endl;
int intIn;
istringstream(stringIn) >> intIn;
cout << "integer = " << intIn << endl;
}
Read in an integer and count the digits directly:
Many other answer do this using log. I'll give one that will properly count the minus sign as a character.
int length_of_int(int number) {
int length = 0;
if (number < 0) {
number = (-1) * number;
++length;
}
while (number) {
number /= 10;
length++;
}
return length;
}
Derived from granmirupa's answer.
Not sure whether it fits your requirement but you could use std::to_string to convert your numeric data to string and then return its length.
For length i assume you mean the number of digits in a number:
#include <math.h>
.....
int num_of_digits(int number)
{
int digits;
if(number < 0)
number = (-1)*number;
digits = ((int)log10 (number)) + 1;
return digits;
}
Or:
int num_of_digits(int number)
{
int digits = 0;
if (number < 0) number = (-1) * number;
while (number) {
number /= 10;
digits++;
}
return digits;
}
Onother option could be this (can works with float too, but the result is not guaranteed):
#include <iostream>
#include <sstream>
#include <iomanip>
...........
int num_of_digits3(float number){
stringstream ss;
ss << setprecision (20) << number;
return ss.str().length();
}
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main(int argc, char **argv)
{
string c;
int k = 0, decval, i;
cout << "Please input your number starting from lowest value number to highest" << endl;
cin >> c;
//the for loop takes a backwards integer and makes it forwards.
for(i = 0; i < c.length(); i++){
decval += (c[i] - '0') * pow(10, k);
++k;
}
cout << decval;
return 0;
}
so my problem is when I input something like 564(wanting to get 465 in return) I get 462. I haven't been able to spot the logic error in the code. Note that I am both new to coding and stack overflow so please don't be too harsh. Any help would be greatly appreciated.
You forgot to initialize decval to 0. It probably contains an arbitrary value which messes up your result.
This code:
(c[i] - '0') * pow(10, k);
Converts an integral type to floating point, performs floating-point math, then converts back to an integral type. (See this question)
You absolutely risk rounding errors along the lines of 59.99999 getting rounded down to 59.
Adjusting your logic to only use integer math will fix it.
int multiplier = 1;
for(i = 0; i < c.length(); i++, multiplier *= 10){
decval += (c[i] - '0') * multiplier;
++k;
}
This is also a solution and is pretty simple I think:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char **argv)
{
string str;
cout << "Please input your number starting from lowest value number to highest" << endl;
cin >> str;
reverse(str.begin(), str.end());
int number = stoi(str);
cout << number << endl;
return 0;
}
Both Drew and nicebyte are correct in what they have pointed out. Just wanted to add that you can do this without k, an extra multiplier variable, calling pow(), or rounding issues:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main(int argc, char **argv)
{
string c;
int decval = 0, i;
cout << "Please input your number starting from lowest value number to highest" << endl;
cin >> c;
//the for loop takes a backwards integer and makes it forwards.
for( i=c.size()-1 ; 0<=i ; --i ) decval = c[i] - '0' + 10*decval;
cout << decval << endl;
return 0;
}
Explanation of for loop:
Take the number 4321 for example. Start at the end of the string, and work backwards. I.e.
After first loop, decval = 1.
After second loop decval = 12.
After third loop, decval = 123.
After fourth loop, decval = 1234.
Each time you are multiplying decval by 10, and adding the new digit. By doing it this way, you don't have to multiply by 10 the first time, 100 the second time, 1,000 the third time, etc.
In this program, I am trying to find the white space of my array, and store that value into a variable then print out that variable. The only function I know to use is the isspace one, and when I used it the error I recieve is: 'isspace' : cannot convert parameter 1 from 'char [80]' to 'int'
Any help would be greatly appreciated!
// Zachary Law Strings.cpp
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>
int main()
{ int x, i,y;
char name[] = "Please enter your name: ";
char answer1 [80];
i=0;
y=0;
cout << name;
cin.getline(answer1, 79);
cout << endl;
x=strlen(answer1);
for (int i = 0; i < x; i++){
cout << answer1[i] << endl;
if (isspace(answer1))
{y=y+1;}}
cout << endl << endl;
cout << setw(80) << answer1;
cout <<y;
return 0;}
Each narrow character classification function takes an int argument that is either non-negative or the special value EOF. Otherwise the behavior is undefined. And with most C++ implementations char is a signed type, so that sufficiently high values (in effect, all characters outside ASCII) become negative.
So cast the argument to unsigned char, after adding the relevant indexing,
if( isspace( (unsigned char) answer1[i] ) )
Then the resulting non-negative value will be implicitly converted to int.
Instead of placing a cast in every invocation of a classification function, consider wrapping them in more C++-friendly fashion, e.g.
auto is_space( char const c )
-> bool
{ return ::isspace( (unsigned char) c ); }
try the below:
for (int i = 0; i < x; i++){
cout << answer1[i] << endl;
if (isspace(answer1[i]))
{y=y+1;}}
As I said earlier, you pass a array instead of a char to isspace function.
isspace function accept:
int isspace ( int c );
/* isspace example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
char c;
int i=0;
char str[]="Example sentence to test isspace\n";
while (str[i])
{
c=str[i];
if (isspace(c)) c='\n';
putchar (c);
i++;
}
return 0;
}
I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}