Segmentaton Fault - c++

I was trying to work on a CodeChef problem (Problem Link :: http://www.codechef.com/problems/K2). The code should take in a input for each test case, process, display the result, before moving to the next testcase. But it is just taking inputs without any output.
I am unable to figure out the error as the g++ compiler isn't giving any.
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;
using std::string;
char baseArr[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
bool isPalin(string number)
{
int len=number.size();
bool flag=true;
for(int i=0; i<len/2, flag==true; i++)
{
if(number[i]==number[len-(i+1)])
continue;
else
{
flag=false;
}
}
return flag;
}
string baseChange(long int number, int base)
{
int i=1;
int rem=0;
string output =" ";
while(number>0)
{
rem=number%base;
number=number/base;
output=baseArr[rem]+output;
}
return output;
}
int main()
{
long int input;
int testcase;
string number;
int i;
bool palin=false;
scanf("%d", &testcase);
while(testcase--)
{
palin=false;
scanf("%ld", &input);
for(i=2; palin==false;i++)
{
{
palin=isPalin(baseChange(input, i));
}
}
printf("%d\n",i);
}
}

You assume that the maximum base will be 16, but this may not be the case. You are probably getting a segmentation fault for accessing baseArr beyond valid index. I have not thought of the solution, but I believe the actualy solution can be implemented without considering any character value for the digits.

A solution to the Palindrome problem:
#include <sstream>
#include <cstdlib>
bool test_palindrome(const std::string& value)
{
for (unsigned int i = 0; i < value.length() / 2; i++)
{
if (value[i] != value[value.length() - 1 - i])
return false;
}
return true;
}
std::string find_palindrome(unsigned long num)
{
std::string ret = "";
for (int i = 2; i <= 32; i++)
{
char buffer[100] = {0};
std::string value = ::itoa(num, buffer, i);
std::cout << "Testing: Base=" << i << " Value=" << value << std::endl;
bool test = test_palindrome(value);
if (test)
{
std::stringstream ss;
ss << value << " (base " << i << ")";
ret = ss.str();
break;
}
}
return ret;
}
int main()
{
unsigned long input = 0;
std::cout << "Enter number to search: ";
std::cin >> input;
std::string palin = find_palindrome(input);
std::cout << std::endl << "Palindrome Found: " << palin << std::endl;
return 0;
}

Related

C++ Code removes first character from vector to int conversion

Below is my code, CP Code represents a template.
For sometime, I have been trying to figure out why the function splitStringOutInt removes the first character. For example, the input is 11 12 13, but the output is [1, 12, 13]. I am very lost, also I am new to C++ so if there is a better method to convert a string line input to an array/vector, please let me know.
// START CP CODE
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string cinLine()
{
cin.ignore();
string tempVar {};
getline(cin, tempVar);
return tempVar;
}
long long int stringToInt(string num)
{
long long int convertedVal = 0;
stringstream strConverterOBJ;
strConverterOBJ << num;
strConverterOBJ >> convertedVal;
return convertedVal;
}
int printIntVector(vector<long long int> lst)
{
cout << "[";
for(int i=0; i<lst.size(); i++){
if(i!=lst.size()-1) {
cout << lst.at(i) << ", ";
}else{
cout << lst.at(i);
}
}
cout << "]" << endl;
return 0;
}
string printStrVector(vector<string> lst)
{
for(int i=0; i<lst.size(); i++){
if(i!=lst.size()-1) {
cout << lst.at(i) << endl;
}else{
cout << lst.at(i);
}
}
return "";
}
vector<long long int> splitStringOutInt(char divider, string str)
{
vector<long long int> intList;
for(long long int j=0; j<=str.length(); j++){
long long int answer {};
if(str[j] == divider || j == str.length()){
answer = stringToInt(str.substr(0, j+1));
str.erase(0,j+1);
intList.insert(intList.end(), answer);
j=0;
}
}
return intList;
}
// END CP CODE
int main()
{
vector<long long int> inp1;
inp1 = splitStringOutInt(' ', cinLine());
printIntVector(inp1);
return 0;
}

C++ Console is blank when program is run

This might be a stupid question I'm still very new to coding. For my CS class I was given code for the basics of a boardgame. When I try to run the code it just comes up blank in my console, I tried to print "check" at the very beginning of main but still nothing prints to the console. No errors come up
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
class square {
private:
int move;
string message;
char symbol;
public:
square();
void print();
int action();
void set(int, char, string);
};
void print_board(square[], int, int);
void read_board(square[]);
void check_position(int &);
const int board_length = 20;
int main() {
cout << "check";
int current_player = 1, roll;
int player1_position = 0, player2_position = 0;
square the_board[board_length];
srand(time(NULL));
read_board(the_board);
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
do {
cout << "\n\n\nPlayer " << current_player << " type enter to roll.\n";
cin.ignore();
roll = 1 + (rand() % 5);
cout << "Player " << current_player << " rolled a " << roll << ".\n";
if (current_player == 1) {
player1_position += roll;
check_position(player1_position);
player1_position += the_board[player1_position].action();
check_position(player1_position);
} else {
player2_position += roll;
check_position(player2_position);
player2_position += the_board[player2_position].action();
check_position(player2_position);
}
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
current_player = (current_player % 2) + 1;
} while ((player1_position < board_length-1) && (player2_position < board_length - 1));
current_player = (current_player % 2) + 1;
cout << "\nPlayer " << current_player << " Wins!!!\n";
cin.ignore();
return 0;
}
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (!infile.eof()) {
infile >> square_number >> square_move >> square_symbol;
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, square_message);
}
}
}
void print_board(square b[], int player_position, int player_number) {
for (int i=0; i < board_length; i++) {
if (i != player_position) {
b[i].print();
} else {
cout << player_number;
}
}
cout << "Goal\n";
for (int i=0; i < board_length; i++) {
cout << "-";
}
cout << "\n";
}
void check_position(int &p) {
if (p < 0) {
p = 0;
}
if (p >= board_length) {
p = board_length - 1;
}
}
square::square() {
symbol = ' ';
move = 0;
message = "";
}
int square::action() {
cout << message << endl;
return move;
}
void square::print() {
cout << symbol;
}
void square::set (int m, char s, string a_message) {
move = m;
symbol = s;
message = a_message;
}
Modify you read_board() to
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (infile >> square_number >> square_move >> square_symbol) {
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, quare_message);
}
}
}
Change cout<<"check"; to cout<<"check"<<endl;
Without the new line added, the out buffer is not flushed before your code gets hung in your read_board function

How to check for non-integer input in multiple inputs

I was working on this program for a while and I can not find a way to make the cin.fail() output "Incorrect input." on 2nd,3rd,4th,... digit of the second binary number. For example "11111 a11" is detected as input fail but "11111 1a1" or "11111 1abfcds" is not detected. It seems to only check the 1st digit. Here is the program.
#include <iostream>
#include <cmath>
using namespace std;
int binary_decimal_1(int n);
int binary_decimal_2(int m);
int decimal_binary(int s);
int main()
{
int n, m, s;
cout << "Input 2 binary numbers" << endl;
cin >> n;
if (cin.fail())
{
cout << "Incorrect input." << endl;
return 0;
}
cin >> m;
if (cin.fail())
{
cout << "Incorrect input." << endl;
return 0;
}
s= binary_decimal_1(n) + binary_decimal_2(m);
cout << "Sum: " << decimal_binary(s) << endl;
return 0;
}
int decimal_binary(int s) /* Function to convert decimal sum to binary result.*/
{
int rem, i=1, binary=0;
while (s!=0)
{
rem=s%2;
s/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
int binary_decimal_1(int n) /* Function to convert binary number 1 to decimal.*/
{
int decimal_1=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal_1 += rem*pow(2,i);
++i;
}
return decimal_1;
}
int binary_decimal_2(int m) /* Function to convert binary number 2 to decimal.*/
{
int decimal_2=0, i=0, rem;
while (m!=0)
{
rem = m%10;
m/=10;
decimal_2 += rem*pow(2,i);
++i;
}
return decimal_2;
}
Input processing terminates on the first non-numeric character encountered.
Once you get a value to parse, use a function to validate it:
template <typename T>
bool convert_to( const std::string& s, T& value )
{
std::istringstream ss( s );
ss >> value >> std::ws;
return ss.eof();
}
--Typed off the top of my head; typos may have occurred.
I fixed my program by using strings and checking those for incorrect input, converting strings to integers and now it works.
#include <iostream>
#include <cmath>
#include <sstream>
using namespace std;
int binary_decimal_1(int n);
int binary_decimal_2(int m);
int decimal_binary(int s);
int main()
{
string n, m;
int s;
cout << "Input 2 binary numbers:" << endl;
cin >> n;
cin >> m;
bool bValidn = true; // Function to check for non numeric input in n.
for (unsigned int nIndex=0; nIndex < n.length(); nIndex++)
if (!isdigit(n[nIndex]))
{
bValidn = false;
cout << "Bad input.";
return 0;
}
bool bValidm = true; // Function to check for non numeric input in m.
for (unsigned int nIndex=0; nIndex < m.length(); nIndex++)
if (!isdigit(m[nIndex]))
{
bValidm = false;
cout << "Bad input.";
return 0;
}
// Now to convert strings into integers.
int intn;
stringstream convertn(n);
if ( !(convertn >> intn) )
intn = 0;
int intm;
stringstream convertm(m);
if ( !(convertm >> intm) )
intm = 0;
// And the hardest part.
s = binary_decimal_1(intn) + binary_decimal_2(intm);
cout << "Sum is: " << decimal_binary(s) << endl << endl;
return 0;
}
int decimal_binary(int s) // Function to convert decimal sum to binary result.
{
int rem, i=1, binary=0;
while (s!=0)
{
rem=s%2;
s/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
int binary_decimal_1(int intn) // Function to convert binary number 1 to decimal.
{
int decimal_1=0, i=0, rem;
while (intn!=0)
{
rem = intn%10;
intn/=10;
decimal_1 += rem*pow(2,i);
++i;
}
return decimal_1;
}
int binary_decimal_2(int intm) // Function to convert binary number 2 to decimal.
{
int decimal_2=0, i=0, rem;
while (intm!=0)
{
rem = intm%10;
intm/=10;
decimal_2 += rem*pow(2,i);
++i;
}
return decimal_2;
}

pthread_create passing in dynamic vector array into argument

how do I cast a void pointer vector array into a vector array?
vector<string>* vArray = new vector<string[numThreads];
p_thread_create(&my_thread[1], NULL, &function, (void)* vArray[1]);
void* function (vector<string> vArray[])
{
//?? casting?
}
when passed in as argument (void)* vArray[1] it says invalid cast...
And can pthread create take in more arguments, say 2, if the function takes 2 parameters? Thanks
Here's my complete code
#include <iostream>
#include <iomanip>
#include <iterator>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <pthread.h>
#include <queue>
using namespace std;
int array[5] = { 0, 0, 0, 0, 0 };
void* readData(void* arg)
{
string fileName = "Wisconsin.txt";
cout << "HERE!"<< endl;
ifstream cities(fileName.c_str());
string line;
while(!cities.eof()){
getline(cities, line);
if(line != "") {
int commaPos = line.find(',');
int popul = atoi(line.substr(commaPos + 2).c_str());
int x = popul;
if (x >= 1 && x <= 999)
{
array[0]++;
} else
if (x >= 1000 && x <= 9999)
{
array[1]++;
} else
if (x >= 10000 && x <= 99999)
{
array[2]++;
} else
if (x >= 100000 && x <= 999999)
{
array[3]++;
} else
if (x >= 1000000)
{
array[4]++;
}
} // end of IF
} // end of while
}
int main()
{
int numThreads;
ifstream ifs("states.txt");
std::string str((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
stringstream ss(str);
int fileCount = 0;
string fileName;
while (ss >> fileName)
{
fileCount++;
}
cout << fileCount;
string* filesArr = new string[fileCount];
ss.clear();
ss.seekg(0, std::ios::beg);
for (int i = 0; i < fileCount; i++)
{
ss >> filesArr[i];
}
cout << "Enter number of threads: ";
cin >> numThreads;
vector<string>* vArray = new vector<string>[numThreads];
for (int i = 0; i < fileCount; i++)
{
vArray[i % numThreads].insert(vArray[i % numThreads].begin(), filesArr[i]);
}
//queue<string>* queueArr = new queue<string>[numThreads];
//for (int i = 0; i < fileCount; i++)
// queueArr[i % numThreads].push(filesArr[i]);
for(int i = 0; i < numThreads; i ++)
{
cout << endl;
cout << "FOR THREAD " << i + 1 << ":" << endl;
for (std::vector<string>::iterator it = vArray[i].begin(); it != vArray[i].end(); it++)
{
cout << *it << endl;
}
}
pthread_t my_thread[numThreads];
int ret = pthread_create(&my_thread[1], NULL, &readData, (void*)(vArray+1));
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
///////////// ERROR HERE!
pthread_join(my_thread[1], ret);
// for (int id = 0; id < numThreads; id++)
// {
//}
pthread_join(my_thread[1]);
cout << endl;
printf("%-20s", "1-999:");
cout << array[0] << endl;
printf("%-20s", "1,000 - 9,999:");
cout << array[1] << endl;
printf("%-20s", "10,000-99,999:");
cout << (array[2]) << endl;
printf("%-20s", "100,000-999,999:");
cout << (array[3]) << endl;
printf("%-20s", "1,000,000+:");
cout << (array[4]) << endl;
//int pos;
//string token;
//while ((pos = s.find(delimiter))
cin.get();
return 0;
}
pthread join doesn't seem to be working now.. compiling it return me: too few arguments to function 'int pthread_join(pthread_t, void**)
After cleaning up your code:
#include <iostream>
#include <vector>
using namespace std;
const int numThreads = 10;
void * thread_body (void * param)
{
// retrieve parameter
string& prm = *(string *)param;
// use it
cout << prm << endl;
return NULL;
}
int main() {
vector<string >threadPrm(numThreads);
vector<pthread_t>threadId (numThreads);
threadPrm[1] = "Hello";
pthread_create(&threadId[1], NULL, thread_body, &threadPrm[1]);
pthread_join (threadId[1], NULL);
return 0;
}
You don't seem to be comfortable with
vectors
pointers and references
variable naming
Also, trying to shut the compiler up with static casts is a sure way to produce silly code.
The point is usually to make the code run, not to compile it at all cost.
Lastly, you can answer your own question about the number of parameters a posix thread can take by reading the manual

C++ "Count the number of collisions at each slot in the hash table"

I'm suppose to create a Dictionary as a Hash Table with Linked List to spell check a text document. I read in the file "words.txt" to create the dictionary. Also, I have to count/display the number of collisions at each slot in the hash table when I load in the dictionary "words.txt"
I'm given the source code for the HashTable Class with Linked List as followed :
hashtable.cpp (#include "listtools.cpp" since its using templates)
#include <iostream>
#include <string>
#include "listtools.h"
#include "listtools.cpp"
#include "hashtable.h"
using LinkedListSavitch::Node;
using LinkedListSavitch::search;
using LinkedListSavitch::headInsert;
using namespace std;
#define HASH_WEIGHT 31
namespace HashTableSavitch
{
HashTable::HashTable()
{
for (int i = 0; i < SIZE; i++)
{
hashArray[i] = NULL;
//array for collisons
collisionArray[i] = 0;
}
}
HashTable::~HashTable()
{
for (int i=0; i<SIZE; i++)
{
Node<string> *next = hashArray[i];
while (next != NULL)
{
Node<string> *discard = next;
next = next->getLink( );
delete discard;
}
}
}
unsigned int HashTable::computeHash(string s) const
{
unsigned int hash = 0;
for (unsigned int i = 0; i < s.length( ); i++)
{
hash = HASH_WEIGHT * hash + s[i];
}
return hash % SIZE;
}
bool HashTable::containsString(string target) const
{
int hash = this->computeHash(target);
Node<string>* result = search(hashArray[hash], target);
if (result == NULL)
return false;
else
return true;
}
void HashTable::put(string s)
{
int count = 0;
int hash = computeHash(s);
if (search(hashArray[hash], s) == NULL)
{
// Only add the target if it's not in the list
headInsert(hashArray[hash], s);
}
else
{
collisionArray[hash]++;
}
void HashTable::printArray()
{
int number;
for(int i = 0; i < SIZE; i++)
{
number = collisionArray[i];
cout << "----------------\n";
cout << "index = " << i << endl;
cout << "Collisions = " << number << endl;
cout << "----------------\n";
}
}
} // HashTableSavitch
my main.cpp file
#include <iostream>
#include <fstream>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <string>
#include "hashtable.h"
using namespace std;
using HashTableSavitch::HashTable;
void upToLow(string & str);
void removePunct(string & str);
int main()
{
HashTable h;
string currWord;
string word;
int countMisspelled = 0;
int countCorrect = 0;
//Get input from words.rtf
ifstream dictionary("words.txt");
//File checking
if (dictionary.fail())
{
cout << "File does not exist" << endl;
cout << "Exit program" << endl;
}
//Create the dictionary as a hash table
while(dictionary >> currWord)
{
h.put(currWord);
}
dictionary.close();
//display collisions
h.printArray();
//Get input from gettysburg_address.txt
ifstream input("gettysburg_address.txt");
//File checking
if (input.fail())
{
cout << "File does not exist" << endl;
cout << "Exit program" << endl;
}
//Spell check gettysburg_address.txt
cout << "Misspelled words : " << endl;
cout << endl;
//If a word is not in the dictionary assume misspelled
while(input >> word)
{
removePunct(word);
upToLow(word);
if(h.containsString(word) == false)
{
countMisspelled++; // Increment misspelled words count
cout << word << " ";
if(countMisspelled % 20 == 0) // Display misspelled words 20 per line
{
cout << endl;
}
}
else
{
countCorrect++; // Increment correct words count
}
}
input.close();
cout << endl;
cout << endl;
cout << "Number of misspelled words : " << countMisspelled << endl;
cout << "Number of correct words : " << countCorrect << endl;
return 0;
}
/*Function to convert uppercase letters to lowercase*/
void upToLow(string & str)
{
for (unsigned int i = 0; i < strlen(str.c_str()); i++)
if (str[i] >= 0x41 && str[i] <= 0x5A)
str[i] = str[i] + 0x20;
}
/*Function to remove punctuation from string*/
void removePunct(string & str)
{
str.erase(remove_if(str.begin(), str.end(), static_cast<int(*)(int)>(&ispunct)),str.end());
}
Is there a simple way to count the number of collisions at each slot when loading in "words.txt" ? If I implement a count variable in the "put" function I can get the total number of collisions, but I'm not quite sure how to count/display the number of collisions at each slot of the hash table. Any help/tips is appreciated.
EDIT :
Followed Joe's advice and now I'm wondering how I could display the number of collisions at each slot. I made a void function to do just that but it displays the number of collisions at each slot to be 0. Anyone know what I should do?
Probably the simplest way is declare an array in an appropriate place
int collisionArray[SIZE];
initialize it to 0 in HashTable::HashTable()
HashTable::HashTable()
{
for (int i = 0; i < SIZE; i++)
{
hashArray[i] = NULL;
collisionArray[i] = 0;
}
}
then increment the appropriate element when a collision is found
void HashTable::put(string s)
{
int count = 0;
int hash = computeHash(s);
if (search(hashArray[hash], s) == NULL)
{
// Only add the target if it's not in the list
headInsert(hashArray[hash], s);
collisionArray[hash]++;
}
}