Tell me how to create different strings in one pointer string like array.
see following two program. 1st one give an errors. what is wrong here?
Kindly correct it.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string *j={"nilesh",
"rohit",
"samir",};
cout<<j<<endl;
}
#include <stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = {"Zara Ali","Hina Ali","Nuha Ali","Sara Ali",};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
Write simply
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s[] = { "nilesh", "rohit", "samir", };
for ( const string &t : s ) cout << t << endl;
}
Also instead of the array you could use standard class std::vector<std::string>
For example
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> v = { "nilesh", "rohit", "samir", };
for ( const std::string &s : v ) std::cout << s << std::endl;
}
Why not try it in this way ?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string j[]={"nilesh",
"rohit",
"samir"};
cout<<j<<endl;
}
Printing j directly wont print all the three names. You need to print j[0], j[1] ...
Related
I'm totally new as a C++ programmer. I met a weird problem.
Our professor asked us to create a mergestrings function and a header file. The code part is simple and works good on my own test code. However, it cannot be compiled on TA's code.
I found it's because I didn't add using namespace std; in my header file.
Here is the header file and function.cc file:
#ifndef mergeStrings_h
#define mergeStrings_h
string mergeStrings(const string &a, const string &b);
#endif
#include <iostream>
#include <string>
using namespace std;
#include "mergeStrings.h"
string mergeStrings(const string &a, const string &b){
int len1 = a.size(), len2 = b.size(), i=0, j=0;
string res = "";
while (i<len1 || j<len2){
if (i<len1)
res.push_back(a[i++]);
if (j<len2)
res.push_back(b[j++]);
}
return res;
};
It COULD be compiled and run on my own test code:
#include <iostream>
#include <string>
using namespace std;
#include "mergeStrings.h"
int main(){
string a = "ace1356789";
string b = "bdf24";
cout<<mergeStrings(a,b)<<endl;
return 0;
}
It COULD NOT be compiled on TA's code.
Here is part of it:
#include <iostream>
#include <string>
#include "mergeStrings.h"
using std::cout;
using std::endl;
using std::string;
const int points_per_test = 10;
void testTwoString(const string &test_name, const string &s1, const string &s2,...
if (mergeStrings(s1, s2) == expected_string) {
total_grade += points_for_this_test;
cout << test_name + " succeeded! +" << points_for_this_test << endl;
} else {
cout << test_name + " failed!" << endl;
}
}
int main() {...
I don't understand why it could be run on my own code.
Your cpp files have using namespace std before #include "mergeStrings.h", so std::string has been pulled into the global namespace.
Your best option is to not write using namespace std (see Why is "using namespace std;" considered bad practice?), but instead fully qualify your types and include the necessary header.
#ifndef mergeStrings_h
#define mergeStrings_h
#include <string>
std::string mergeStrings(const std::string &a, const std::string &b);
#endif
#include <iostream>
#include <string>
#include "mergeStrings.h"
std::string mergeStrings(const std::string &a, const std::string &b){
int len1 = a.size(), len2 = b.size(), i=0, j=0;
std::string res = "";
while (i<len1 || j<len2){
if (i<len1)
res.push_back(a[i++]);
if (j<len2)
res.push_back(b[j++]);
}
return res;
};
#include <iostream>
#include <string>
#include "mergeStrings.h"
int main(){
std::string a = "ace1356789";
std::string b = "bdf24";
cout<<mergeStrings(a,b)<<endl;
return 0;
}
I need to provide a CFG class in a separate file, but I'm unsure how to compile it together with the associated .h and the main program.
I've #includeed the .h file and I've asked for both files at the command line, but I'm not sure why this is wrong for compiling them together.
Thoughts?
CFG.cpp:
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class CFG
{
public:
string code[25];
char startNT;
//private:
CFG(string inCode[], int stringLen)
{
for (int a = 0; a < stringLen; a++)
{
//cout << inCode[a] << endl;
this->code[a] = inCode[a];
}
for (int a = 0; a < stringLen; a++)
{
cout << this->code[a] << endl;
}
}
char getStartNT()
{
return startNT;
}
void setStartNT(char stNT)
{
startNT = stNT;
}
bool processData(string inString, string wkString)
{
//Our recursive function
return true;
}
void garbage()
{
return;
}
};
CFG.h:
#ifndef _cfg_h_
#define _cfg_h_
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class CFG
{
public:
string code[25];
char startNT;
CFG(string inCode[], int stringLen);
char getStartNT();
void setStartNT(char stNT);
bool ProcessData(string inString, string wkString);
void garbage();
};
#endif
cfg_entry.cpp:
#include <stdio.h>
#include <iostream>
#include "cfg.h"
using namespace std;
int main()
{
string inArray[5];
inArray[0] = "test0";
inArray[1] = "test1";
inArray[2] = "test2";
inArray[3] = "test3";
inArray[4] = "test4";
CFG * cfg1 = new CFG(inArray, 5);
cfg1->garbage();
return 0;
}
Compile errors:
art#tv:~/Dropbox/Weber/CS 4110/Individual Assignment 2$ g++ -g -std=c++11 -Wall -o cfg_entry cfg.cpp cfg_entry.cpp
/tmp/ccICQEd0.o: In function `main':
/home/art/Dropbox/Weber/CS 4110/Individual Assignment 2/cfg_entry.cpp:15: undefined reference to `CFG::CFG(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*, int)'
/home/art/Dropbox/Weber/CS 4110/Individual Assignment 2/cfg_entry.cpp:16: undefined reference to `CFG::garbage()'
collect2: error: ld returned 1 exit status
I found my issue. In my case, the header file was defining the class and the .cpp file was re-defining it again, trying to create 2 instances of the CFG class. The .h needed to handle the class declaration and variable instantiation while the .cpp handles only the function definitions.
cfg.h:
#ifndef _cfg_h_
#define _cfg_h_
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class CFG
{
private:
string code[25];
char startNT;
public:
CFG(string inCode[], int stringLen);
char getStartNT();
void setStartNT(char stNT);
bool processData(string inString, string wkString);
void garbage();
};
#endif
cfg.cpp:
#include <iostream>
#include <stdio.h>
#include <string>
#include "cfg.h"
using namespace std;
CFG::CFG(string inCode[], int stringLen)
{
for (int a = 0; a < stringLen; a++)
{
//cout << inCode[a] << endl;
this->code[a] = inCode[a];
}
for (int a = 0; a < stringLen; a++)
{
cout << this->code[a] << endl;
}
}
char CFG::getStartNT()
{
return startNT;
}
void CFG::setStartNT(char stNT)
{
startNT = stNT;
}
bool CFG::processData(string inString, string wkString)
{
//Our recursive function
return true;
}
void CFG::garbage()
{
return;
}
I'm trying to devise a function that randomly selects three of the five strings and displays them on the screen. Here's what I have so far. It runs but nothing prints to the screen.
#include "BoxOfProduce.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>
using namespace std;
BoxOfProduce::BoxOfProduce()
:choices{""}, bundles{""}
{
}
vector<string> BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
vector<string> random;
for(int i = 0; i < 3; i++)
{
random.push_back(choices[rand() % 5]);
}
return random;
}
#ifndef BOXOFPRODUCE_H
#define BOXOFPRODUCE_H
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class BoxOfProduce
{
public:
BoxOfProduce();
string getBundles();
void setBundles(string b);
vector<string> randomize();
private:
string bundles[3];
const string choices[5];
string random;
};
#endif // BOXOFPRODUCE_H
#include <iostream>
#include "BoxOfProduce.h"
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>
using namespace std;
int main()
{
srand(time(0));
BoxOfProduce bo;
bo.randomize();
auto vector<string> randomResult = bo.randomize();
for (const auto& result : randomResult){
cout << result << endl;
}
}
I have updated my code now and still no print output. Although I am getting an error:
error: range-based 'for' loops are not allowed in C++98 mode
I have never worked with auto before. So any help on this would be appreciated.
Your code should not compile. g++ emits the following error:
return random;
error: could not convert ‘random’ from ‘long int (*)()throw ()’
The random variable is local to your for-body. You should give it a greater scope:
string random;
for(int i = 0; i < 3; i++)
{
random = choices[rand() % 5];
}
return random;
To produce the 3 results, you need to return a vector of string like
#include<ctime>
#include<cstdlib>
#include<string>
#include<memory>
#include<vector>
#include<iostream>
using namespace std;
std::vector<string> randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
std::vector<string> random;
for(int i = 0; i < 3; i++)
{
random.push_back(choices[rand() % 5]);
}
return random;
}
int main()
{
srand(time(0));
randomize();
std::vector<string> randomResult = randomize();
for (std::vector<string>::const_iterator iter = randomResult.begin(), iterEnd = randomResult.end();
iter != iterEnd; ++iter)
cout << *iter << endl;
return 0;
}
The scope of string random is only inside the for loop in your code.
try this:
string BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
string random = "";
for(int i = 0; i < 3; i++)
{
random = choices[rand() % 5];
}
return random;
}
int main()
{
srand(time(0));
BoxOfProduce bundle1;
bundle1.randomize();
cout << bundle1.randomize() << endl;
}
The code you provided shouldn't even compile. Try this:
string BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
string random;
for(int i = 0; i < 3; i++)
{
random = choices[rand() % 5];
}
return random;
}
int main()
{
srand(time(0));
BoxOfProduce bundle1;
bundle1.randomize();
cout << bundle1.randomize() << endl;
}
The braces { } define a scope. After that scope, the variables you define inside it are destroyed. So you should define that variable before you start that scope.
Probably the reason it compiled is that you already have another variable string random inside the body of the class BoxOfProduce. So you either define that string random outside the scope, like I did, or you just remove the string before random, and then the compiler will use the variable from the class body.
I want to point an array in c++ , is it possible ?
My main code :
#include "ArrayPointerClass.h"
#include "stdafx.h"
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
float arr[2];
ArrayPointerClass::pointingArray(&arr);
return 0;
}
ArrayPointerClass.h
#pragma once
static class ArrayPointerClass
{
public:
ArrayPointerClass();
~ArrayPointerClass();
static void pointingArray(float* arr[2]);
};
ArrayPointerClass.cpp
#include "stdafx.h"
#include "ArrayPointerClass.h"
ArrayPointerClass::ArrayPointerClass()
{
}
ArrayPointerClass::~ArrayPointerClass()
{
}
void ArrayPointerClass::pointingArray(float* arr[2]){
float newArray[2] = { 2.2f, 2.2f };
*arr = newArray;
}
I've got this error :
Error 3 error C2653: 'ArrayPointerClass' : is not a class or namespace name c:\users\alex\documents\visual studio 2013\projects\pointerarray\pointerarray\pointerarray.cpp 13 1 PointerArray
Error 3 error C3861: 'pointingArray': identifier not found c:\users\alex\documents\visual studio 2013\projects\pointerarray\pointerarray\pointerarray.cpp 13 1 PointerArray
I know in C++ arrays ,arrays without length defined are not allowed . is it the reason ?
Thanks for your support
There is no way to create a static class in c++. static keyword can be applied to objects and functions.
And each array name is a pointer. Therefore subscripts cannot be given in the parameter. It is sufficient to provide the pointer type.
The modified code which works:
#include <iostream>
#include <string>
using namespace std;
class ArrayPointerClass
{
public:
ArrayPointerClass();
~ArrayPointerClass();
static void pointingArray(float* arr);
};
ArrayPointerClass::ArrayPointerClass()
{
}
ArrayPointerClass::~ArrayPointerClass()
{
}
void ArrayPointerClass::pointingArray(float* arr){
float newArray[2] = { 2.2f, 2.2f };
arr = newArray;
}
int main()
{
float arr[2];
ArrayPointerClass obj;
obj.pointingArray(arr);
return 0;
}
*arr = newArray; will not work you can't copy a C array like that .
You could have done memcpy() or std::copy() like;
memcpy( newArray, arr, 2);
std::copy( newArray, newArray+2, arr);
Thanks everybody for your answers (even there were partially working)
I found my self a solution
// PointerArray.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int* test() {
int size_needed = 2;
int* a = new int[size_needed];
a[0] = 0;
a[1] = 0;
return a;
}
int main()
{
//int arr[2] = { 1, 1 };
int* arr = test();
for (int i = 0; i < 2; i++){
cout << arr[i] << std::endl;
}
cin.get();
return 0;
}
I've been recently working on a program which consists basically of 24 variations of one function(below). Everything gets executed perfectly apart from the part where I try to compare functions(with eachother). I found out that it is possible to be done by writing 24 if-else statements, yet I am certain there is a shorter way. I've also tried with vectors but no luck for now. Thanks for any help!
one of 24 functions:
int funk1()
{
ifstream myfile ("file.txt");
string line;
int i;
class1 obj1;
obj1.atr1= "Somename";
obj1.atr2="GAATTC";
while (getline(myfile, line))
{
i = countSubstring(line, obj1.atr2);
obj1.sum += i;
};
cout<<obj1.sum<<": "<<obj1.atr1<<"\n";
return obj1.sum;
}
The main function:
int main(){
funk1();
funk2();
funk3();
funk4();
funk5();
funk6();
funk7();
funk8();
funk9();
funk10();
funk11();
funk12();
funk13();
funk14();
funk15();
funk16();
funk17();
funk18();
funk19();
funk20();
funk21();
funk22();
funk23();
funk24();
//This is one way to do it
if (funk18() > funk1())
{
cout<<funk18<<" is the biggest";
}
//...
}
Here is a clean and elegant c++11 solution:
#include <iostream>
#include <functional>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
using MyFunc = std::function<int()>;
int f1() { return 1; }
int f2() { return 15;}
int f3() { return 3; }
int main() {
std::vector<MyFunc> my_functions = {f1, f2, f3};
int max = std::numeric_limits<int>::min();
for (auto const &f : my_functions) {
max = std::max(max, f());
}
cout << max << endl;
return 0;
}
if you want to store the results from functions instead, you could do:
std::vector<int> my_results;
my_results.reserve(my_functions.size());
for (auto const &f : my_functions) {
my_results.push_back(f());
}
auto max_it = std::max_element(std::begin(my_results), std::end(my_results));
cout << *max_it << endl;