strlen function incompatible w/loop, loop variable incompatible - c++

Ok I've been looking everywhere and I can't find the proper way to do this. I simply want to take in a string, put that string in the array and output the contents. However, I want to do it dependent on the size of the string which the user enters in. And I was getting weird errors such as incompatibility and I would like to know why please, thank you.
#include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
int x = 4000;
string y;
cout << "Enter value";
getline(cin, y);
array<char, strlen(y)>state;
for(int i=0; i<strlen(y); ++i)
cout << state[i] << ' ';
system("PAUSE");
return 0;
}

std::array needs a compile-time size, so cannot be instantiated with strlen. Furthermore, strlen does not work with std::string, it expects a pointer to char, pointing to the beginning of null terminated string.
You could use an std::vector<char> instead:
std::string y;
std::cout << "Enter value";
std::getline(std::cin, y);
std::vector<char> state(y.begin(), y.end());
for(int i = 0; i < state.size(); ++i)
std::cout << state[i] << ' ';
On the other hand, why not just use the string y directly? Do you really need the "array"?
for(int i = 0; i < y.size(); ++i)
std::cout << y[i] << ' ';

std::array is a wrapper template class around a C static array. This means that it's dimensions must be known at build time (not runtime).
Here's a short version of a working code that's also a little faster since string::length() is called once.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string y;
cout << "Enter value";
getline(cin, y );
for( size_t i = 0, yLen = y.length(); i < yLen; ++i )
cout << y[i] << ' ';
system( "PAUSE" );
return 0;
}
If you like pointer tricks and take advantage that string's buffer is contiguous in memory (by the C++ standard) your code can look like:
int main()
{
string y;
cout << "Enter value";
getline(cin, y );
for( const char* p = &y[0]; *p; ++p )
cout << *p << ' ';
system( "PAUSE" );
return 0;
}

i hope it will work..
#include "stdafx.h"
#include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
int x = 4000;
string y;
cout << "Enter value";
getline(cin, y );
char *b = new char[y.length()];
int j=y.length();
//array< char, strlen(y)>state;
for( int i = 0; i<j; ++ i )
{//whatever uu want
}
//cout << state[i] << ' ' ;
system( "PAUSE" );
return 0;
}

Related

How to read more than one line of input?

So I have built a small basic data encrypter (for learning purposes only). It is working perfectly fine but it reads only a single line of input. Is it my Editor problem or my code have some issues.
ps: I use CodeBlocks
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
std::string str;
char enc;
int word;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
cout << "Enter a Word: ";
getline(cin, str);
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(int i = 0; i < str.length(); i++){
int randomAdd[5] = {5,6,2,3,2};
int size = sizeof(randomAdd)/sizeof(randomAdd[0]);
// for(int j = 0; j < 5; j++){
word = str.at(i);
if(i%5 == 0){
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
return 0;
}
This works
Hello World
But I cannot enter this
Hello World
Have a nice day
because then the program exits command prompt without any error or message.
How can I read more than one line?
You can do as
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
cout << str << endl;
}
return 0;
}
This code sample allows you to input multiple lines interactively from the command line/shell
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
char enc;
int word;
vector<string> myInput;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
while (str != "Enigma")
{
cout << "Enter a line (Write Enigma to exit input): ";
getline(cin, str);
myInput.push_back(str);
}
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(auto & myInputLine : myInput)
{
str = myInputLine;
for (size_t i = 0; i < str.length(); i++) {
int randomAdd[5] = { 5,6,2,3,2 };
int size = sizeof(randomAdd) / sizeof(randomAdd[0]);
word = str.at(i);
if (i % 5 == 0) {
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
}
return 0;
}
The input is finished if Enigma is written.
All input is stored in the vector container of the STL, see vector.
Afterwards, all the lines are encrypted by your algorithm.
Hope it helps?

Count a string from 1 instead of 0 in c++

do you know how can I start to count a string from 1 and not from 0 in c++? for example, xyz are on iterations 0,1,2.. but i need them to be on 1,2,3. I know you can put cout << i+1; but is there any other way to do this with strlen(s+1)?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 0; i < n; ++i)
cout<<i<<": "<<s[i]<<"\n";
return 0;
}
i+1 is the way to go. An alternate method is starting your loop with 1 instead and accessing the array at element i-1, but that's a bit silly:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 1; i <= n; ++i) // i = 1 not 0
cout<<i<<": "<<s[i-1]<<"\n";
return 0;
}
In C++, you shouldn't use C-Strings. Instead, use std::string:
#include <iostream>
#include <string>
int main()
{
std::string s;
std::getline(std::cin, s);
for (int i = 0; i < s.length(); ++i)
std::cout << i + 1 << ": " << s[i] << '\n' ;
return 0;
}
As others have said, the simple answer is really just accept you start from zero - however, for an actually solution you can use boost-range and use an index adaptor with an argument of '1'.
std::string str;
std::getline(std::cin, str);
for (const auto & element : str | boost::adaptors::indexed(1)) {
std::cout << element.index()
<< " : "
<< element.value()
<< std::endl;
}

C++ convert string array to integers, then sum int array

I need to pass an user input integer to a sumTotal(& userInt) function.
If the int is 2341 I need to sum 2+3+4+1 = 10 and return the value to main!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// The program needs to input an integer like 2341, then sum it as 2+3+4+1 + 10
// I am in putting an integer and will pass it to a funtion by &.
int main()
{
string strNumber;
int intNumber = 0;
cout << "Enter your number: ";
cin >> intNumber;
// programming the logic for sumTotal(& intNumber) function before creating
strNumber = to_string(intNumber);
cout << "Your number is: " << strNumber << endl;
cout << "Your numbers length: " << strNumber.length() << " digits" << endl;
// here I need to convert the string array to an integer array
for (int i = 0; i < strNumber.length(); ++i){
intNumber[&i] = strNumber[i] - '0';
cout << "Element [" << i << "] contains: " << strNumber[i] << endl;
}
// next a recursive function must sum the integer array
// I am taking an online course and cant afford a tutor please help!
system("pause");
return 0;
}
if you want recursion ,you don't need any string work,try this :
#include <iostream>
using namespace std;
int recSum(int);
int main(){
int i;
cin>>i;
cout<<recSum(i);
return 0;
}
int recSum(int i){
return i==0?0:i%10+recSum(i/10);
}
recursion on array version
#include <iostream>
using namespace std;
int recSum(int* ary,int len){
return len<0?0:ary[len]+recSum(ary,len-1);
}
int main(){
int j[]={1,2,3,4,5,6,7,8,9,10};
cout<<recSum(j,9);
}
A simple and efficient method is to keep the number as a string and access the digits one at a time.
Note the equation:
digit_number = digit_character - '0';
Also, knowing that when summing digits, the order is irrelevant. So, we have:
sum = 0;
for (i = 0; i < string.length(); ++i)
{
sum += string[i] - '0';
}
A string is an array of chars. To convert a char to an int you have to do 'char' - '0'.
I wrote a couple of versions.
Pick whichever one you like best.
#include <iostream>
#include <string>
int main()
{
std::string str = "1234";
int sum = 0;
//pre C++11
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//C++11
sum = 0;
for (auto i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//ranged-for
sum = 0;
for (const auto &i : str)
sum += (i - '0');
std::cout << "Sum: " << sum;
std::cin.get();
}

Error: comparison between signed and unsigned integer expressions?

I'm getting this error on this line of code. Please help me solve it.
for (int i=0; i=((Main.size())-1); i++) {
Main code..
#include <istream>
#include <fstream>
#include <vector>
#include <algorithm>
#include "data.hpp"
using namespace std;
int main() {
vector<double> Main;
int count;
string lineData;
double tmp;
ifstream myfile ("sheffield.data", ios::in);
//double number;
myfile >> count;
for(int i = 0; i < count; i++) {
myfile >> tmp;
Main.push_back(tmp);
cout << count;
}
cout << "Numbers:\n";
cout << Main.size();
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
cin.get();
return 0;
}
The type of value returned by member function size is unsigned while i is declared as signed.
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
So instead of int i use at least unsigned int i or size_t i .It would be even better if you would use the type that is defined in class std::vector that is std::vector<double>::size_type i
Also in the condition part of the loop you are using the assignment operator = instead of the comparison operator == But if you would update the operator the condition will be wrong until size() will be equal to 0. Instead of operator == you have to use <=
The loop should look the following way
for ( std::vector<double>::size_type i = 0; i < Main.size(); i++ ) {
cout << Main[i] << '\n';
}
Also instead this for statement you could use the range based for statement that looks much simpler. For example
for ( double x : Main ) {
cout << x << '\n';
}
The i is of type int(signed) and the result of Main.size() of unsigned int, probably size_t depending on the tye of Main.
If you compare them in the for-loop, you have your explanation.
But be aware: a single = is an assignment, not a comparison.
Fix(probably):
for (unsigned int i=0; i < Main.size(); i++) {
You could also consider using iterators instead:
cout << "Numbers:\n";
cout << Main.size();
for (vector<double>::const_iterator i = Main.begin(); i != Main.end(); ++i) {
cout << *i << '\n';
}
(And as a side note, naming a variable (Main) with a capital letter is somewhat confusing!)

Storing Chars Into Strings in C++

So right now I have this code that generates random letters in set increments determined by user input.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
static const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
while(true)
{
for (int x = 0; x < sLength; x++)
{
cout << genRandom();
}
cout << endl;
}
}
I'm looking for a way to store the first (user defined amount) of chars into a string that I can use to compare against another string. Any help would be much appreciated.
Just add
string s(sLength, ' ');
before while (true), change
cout << genRandom();
to
s[x] = genRandom();
in your loop, and remove the cout << endl; statement. That will replace all of the printing by putting the characters into s.
Well, how about this?
std::string s;
for (int x = 0; x < sLength; x++)
{
s.push_back(genRandom());
}
#include<algorithm>
#include<string>
// ...
int main()
{
srand(time(0)); // forget me not
while(true) {
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
string r(sLength, ' ');
generate(r.begin(), r.end(), genRandom);
cout << r << endl;
}
}