I've recently encountered a problem with sscanf(), which I'm using to parse a polynomial.
The problem is, that this sscanf returns 1:
if (sscanf(pTemp, "%lfx\0", &tempBuf)) {
while reading the following:
4x^2\0-4x\01\t\0\0\0\0\0\0\0\0\0
but it's supposed to return 0 (obviously).
And this part of code has successfully read the right thing just before that, so I have no clue on what goes wrong.
I've tried replacing \t with such things, as * /, this didn't help. sscanf keeps recognizing 1(something) as %lfx, while supposed to return 0 and move forward.
What's the problem with it and how can I solve it except rewriting the code without using sscanf?
Here is the code itself(comments and printfs are in Russian, but they don't mean anything to the problem):
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
typedef struct polynom {
double* coeffs;
int power;
} polynom;
void main() {
setlocale(LC_ALL, "RUS");
char bufRead, flagNeg = 0, numExp = 0, xExp = 0, powExp = 0, xNotExp = 0, powAlrSet = 0, *tempReadStr, *pTemp, tempReadC = 0;
int power = 0, apprAcc = 0, cnt = 0, prolongCnt = 0;
double tempBuf = 0;
polynom* polynomIn, * polynomDer, * polynom0;
tempReadStr = calloc(52, sizeof(char));
if (!tempReadStr) {
printf("Не хватает памяти для строки ввода. Попробуйте закрыть все ненужные приложения и повторить попытку.");
return 0;
}
printf("Введите многочлен: ");
//ввод самого многочлена в строку
while (1) {
scanf("%c", &tempReadC);
if (tempReadC == '\n') {
tempReadStr[cnt++] = ' ';
break;
}
if (!isdigit(tempReadC) && (tempReadC != '+') && (tempReadC != '-') && (tempReadC != 'x') && (tempReadC != '^')) {
printf("Недопустимый символ: %c. Проверьте правильность ввода.", tempReadC);
return;
}
else {
if (cnt < 50 + prolongCnt * 50) {
if ((cnt != 0) && (tempReadC == '-')) {
tempReadStr[cnt++] = ' ';
}
if (tempReadC == '+') {
tempReadStr[cnt++] = ' ';
}
else {
tempReadStr[cnt++] = tempReadC;
}
}
else {
pTemp = realloc(tempReadStr, (52 + (++prolongCnt * 50)) * sizeof(char));
if (!pTemp) {
printf("Не хватает памяти для строки ввода. Попробуйте закрыть все ненужные приложения и повторить попытку.");
return 0;
}
tempReadStr = pTemp;
for (int j = 52 + ((prolongCnt - 1) * 50); j < 52 + (prolongCnt * 50); j++) {
tempReadStr[j] = '\0';
}
if ((cnt != 0) && (tempReadC == '-')) {
tempReadStr[cnt++] = ' ';
}
if (tempReadC == '+') {
tempReadStr[cnt++] = ' ';
}
else {
tempReadStr[cnt++] = tempReadC;
}
}
}
}
//printf("\n%s", tempReadStr);
pTemp = strtok(tempReadStr, " ");
//блок интерпретации полученной строки
while (1) {
if (!pTemp) {
break;
}
if (sscanf(pTemp, " ")) {
break;
}
/*if (sscanf(pTemp, "+")) {
}*/
if (sscanf(pTemp, "%lfx^%d", &tempBuf, &power) == 2) {
if (powAlrSet) {
if (polynomIn->power < power) {
printf("Встечена степень, большая, чем первая введённая. Введите многочлен, начиная с наибольшей степени.");
return;
}
else {
polynomIn->coeffs[power] = tempBuf;
}
}
else {
polynomIn = calloc(1, sizeof(polynom));
if (!polynomIn) {
printf("Ошибка выделения памяти.");
return;
}
polynomIn->power = power;
polynomIn->coeffs = calloc(power + 1, sizeof(double));
if (!polynomIn->coeffs) {
printf("Ошибка выделения памяти.");
return;
}
powAlrSet = 1;
polynomIn->coeffs[power] = tempBuf;
}
pTemp = strtok(NULL, " ");
continue;
}
if (sscanf(pTemp, "x^%d", &power)) {
if (powAlrSet) {
if (polynomIn->power < power) {
printf("Встечена степень, большая, чем первая введённая. Введите многочлен, начиная с наибольшей степени.");
return;
}
else {
polynomIn->coeffs[power] = 1;
}
}
else {
polynomIn = calloc(1, sizeof(polynom));
if (!polynomIn) {
printf("Ошибка выделения памяти.");
return;
}
polynomIn->power = power;
polynomIn->coeffs = calloc(power + 1, sizeof(double));
if (!polynomIn->coeffs) {
printf("Ошибка выделения памяти.");
return;
}
powAlrSet = 1;
polynomIn->coeffs[power] = 1;
}
pTemp = strtok(NULL, " ");
continue;
}
if (sscanf(pTemp, "-x^%d", &power)) {
if (powAlrSet) {
if (polynomIn->power < power) {
printf("Встечена степень, большая, чем первая введённая. Введите многочлен, начиная с наибольшей степени.");
return;
}
else {
polynomIn->coeffs[power] = -1;
}
}
else {
polynomIn = calloc(1, sizeof(polynom));
if (!polynomIn) {
printf("Ошибка выделения памяти.");
return;
}
polynomIn->power = power;
polynomIn->coeffs = calloc(power + 1, sizeof(double));
if (!polynomIn->coeffs) {
printf("Ошибка выделения памяти.");
return;
}
powAlrSet = 1;
polynomIn->coeffs[power] = -1;
}
pTemp = strtok(NULL, " ");
continue;
}
if (sscanf(pTemp, "%lfx", &tempBuf)) {
if (powAlrSet) {
polynomIn->coeffs[1] = tempBuf;
}
else {
polynomIn = calloc(1, sizeof(polynom));
if (!polynomIn) {
printf("Ошибка выделения памяти.");
return;
}
polynomIn->power = 1;
polynomIn->coeffs = calloc(2, sizeof(double));
if (!polynomIn->coeffs) {
printf("Ошибка выделения памяти.");
return;
}
powAlrSet = 1;
polynomIn->coeffs[1] = tempBuf;
}
pTemp = strtok(NULL, " ");
continue;
}
if (sscanf(pTemp, "x")) {
if (powAlrSet) {
polynomIn->coeffs[1] = 1;
}
else {
polynomIn = calloc(1, sizeof(polynom));
if (!polynomIn) {
printf("Ошибка выделения памяти.");
return;
}
polynomIn->power = 1;
polynomIn->coeffs = calloc(2, sizeof(double));
if (!polynomIn->coeffs) {
printf("Ошибка выделения памяти.");
return;
}
powAlrSet = 1;
polynomIn->coeffs[1] = 1;
}
pTemp = strtok(NULL, " ");
continue;
}
if (sscanf(pTemp, "-x")) {
if (powAlrSet) {
polynomIn->coeffs[1] = -1;
}
else {
polynomIn = calloc(1, sizeof(polynom));
if (!polynomIn) {
printf("Ошибка выделения памяти.");
return;
}
polynomIn->power = 1;
polynomIn->coeffs = calloc(2, sizeof(double));
if (!polynomIn->coeffs) {
printf("Ошибка выделения памяти.");
return;
}
powAlrSet = 1;
polynomIn->coeffs[1] = -1;
}
pTemp = strtok(NULL, " ");
continue;
}
if (sscanf(pTemp, "%lf", &tempBuf)) {
if (!powAlrSet) {
printf("Ввод многочлена принято начинать со старшей степени.");
return;
}
else {
polynomIn->coeffs[0] = tempBuf;
}
}
}
printf("Вы ввели многочлен:\n");
for (int i = power; i >= 0; i--) {
if (polynomIn->coeffs[i]) { // != 0
if ((polynomIn->coeffs[i] > 0) && (i != power))
printf("+");
if (i) { // != 0
if (polynomIn->coeffs[i] != 1) {
if (polynomIn->coeffs[i] != -1) {
if (i != 1) {
printf("%.0lfx^%d", polynomIn->coeffs[i], i);
}
else printf("%.0lfx", polynomIn->coeffs[i]);
}
else if (i != 1) {
printf("-x^%d", i);
}
else printf("-x");
}
else if (i != 1) {
printf("x^%d", i);
}
else printf("x");
}
else {
if (polynomIn->coeffs[i]) {
printf("%.0lf", polynomIn->coeffs[i]);
}
}
}
}
}
It should give you the polynomial you enter. I tried with 4x^2-4x+1, and it gave me 4x^2+x.
Well, I don't know, what's the reason with sscanf(), because it tends to ignore even what goes before the first formatted input, so I've just replaced all my "-", "x", "^", with %c scanning chars to variables, which values I've checked right after that. And that worked.
Related
I'm currently trying to make use of the Minimax Algorithm and create a "Unbeatable Computer Player". I'm banging my head with this one for hours now and I cant seem to figure out why the "Computer" is going in order and not making the right decisions. Does anybody have an idea? maybe something sticks out for you I can't put my finger on what's wrong honestly. I bet it has something to do with the recursive call but I'm lost here.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char BOARD[9][4];
void createBoard(){
for(int i = 0;i < 9;i++){
strcpy(BOARD[i], "[]");
}
strcpy(BOARD[6], "[X]");
strcpy(BOARD[1], "[O]");
strcpy(BOARD[3], "[X]");
}
void printBoard(){
printf("\n\n");
for(int i = 0;i < 9;i++){
printf("%s", BOARD[i]);
if((i + 1) % 3 == 0){
printf("\n");
}
}
printf("\n\n");
}
void makeMove(char* player, int position){
char playerFinal[5];
strcpy(playerFinal, "[");
strcat(playerFinal, player);
strcat(playerFinal, "]");
if(strcmp(BOARD[position], "[]") == 0){
strcpy(BOARD[position], playerFinal);
}
}
bool movesLeft(){
for(int i = 0;i < 9;i++){
if(strcmp(BOARD[i], "[]") == 0){
return true;
}
}
return false;
}
char* isWinner(){
for(int i = 0;i < 9;i = i + 3){
if(strcmp(BOARD[i], BOARD[i + 1]) == 0 && strcmp(BOARD[i + 1], BOARD[i + 2]) == 0){
if(strcmp(BOARD[i], "[X]") == 0){
return "X";
}
else if(strcmp(BOARD[i], "[O]") == 0){
return "O";
}
}
}
for(int i = 0;i < 3;i++){
if(strcmp(BOARD[i], BOARD[i + 3]) == 0 && strcmp(BOARD[i + 3], BOARD[i + 6]) == 0){
if(strcmp(BOARD[i], "[X]") == 0){
return "X";
}
else if(strcmp(BOARD[i], "[O]") == 0){
return "O";
}
}
}
if(strcmp(BOARD[0], BOARD[4]) == 0 && strcmp(BOARD[4], BOARD[8]) == 0){
if(strcmp(BOARD[0], "[X]") == 0){
return "X";
}
else if(strcmp(BOARD[0], "[O]") == 0){
return "O";
}
}
if(strcmp(BOARD[2], BOARD[4]) == 0 && strcmp(BOARD[4], BOARD[6]) == 0){
if(strcmp(BOARD[2], "[X]") == 0){
return "X";
}
else if(strcmp(BOARD[2], "[O]") == 0){
return "O";
}
}
if(!movesLeft()){
return "tie";
}
return "";
}
int minimax(bool isMaximizing){
char* winner = isWinner();
printf("Function Called\n");
printf("%s", winner);
if(strcmp(winner, "O") == 0){
return 10;
}
if(strcmp(winner, "X") == 0){
return -10;
}
if(strcmp(winner, "tie") == 0){
return 0;
}
if(isMaximizing){
int score;
int bestScore = -1000000;
for(int i = 0;i < 9;i++){
if(strcmp(BOARD[i], "[]") == 0){
makeMove("O", i);
score = minimax(false);
strcpy(BOARD[i], "[]");
if(score > bestScore){
bestScore = score;
}
}
}
return bestScore;
}
else{
int score;
int bestScore = 1000000;
for(int i = 0;i < 9;i++){
if(strcmp(BOARD[i], "[]") == 0){
makeMove("X", i);
score = minimax(true);
strcpy(BOARD[i], "[]");
if(score < bestScore){
bestScore = score;
}
}
}
return bestScore;
}
}
void bestMove(){
int bestScore = -1000;
int position;
for(int i = 0;i < 9;i++){
if(strcmp(BOARD[i], "[]") == 0){
int score;
makeMove("O", i);
score = minimax(false);
strcpy(BOARD[i], "[]");
printf("Position %d\n", i);
printf("Best Score %d\n", bestScore);
printf("Score %d\n", score);
if(score > bestScore){
bestScore = score;
position = i;
}
}
}
makeMove("O", position);
}
int main(){
int position;
createBoard();
printBoard();
bool player = true;
char* winner = "";
while(strcmp(winner, "") == 0){
if(player){
printf("Its the Players Turn\nChoose a Position: ");
scanf("%d", &position);
makeMove("X", position -1);
player = false;
winner = isWinner();
}
else{
printf("Its the Computers Turn");
bestMove();
player = true;
winner = isWinner();
}
printBoard();
}
printf("The Winner is: %s\n", winner);
return 0;
}
Hi I am completely stuck on this basic calculator. It runs almost perfectly but something goes wrong in the stack when I try inputting "5 / 5 + 9 * 2". The 1 from 5 / 5 seems to disappear when it is supposed to be addes to the 18 for the last loop. Happens for simular inputs like 2 * 2 - 9 / 2. Just need help finding this weird error that I have spent many hours trying to figure out with no luck! Thank you!
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <limits.h>
#include <curses.h>
#include<ctype.h>
struct StackNode
{
char* data;
struct StackNode* next;
};
struct StackNode* newNode(char* data)
{
struct StackNode* stackNode =
(struct StackNode*) malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(struct StackNode *root)
{
return !root;
}
void push(struct StackNode** root, char* data)
{
struct StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
printf("%s pushed to stack\n", data);
}
char* pop(struct StackNode** root)
{
if (isEmpty(*root))
return NULL;
struct StackNode* temp = *root;
*root = (*root)->next;
char* popped = temp->data;
free(temp);
printf("Popped: %s\n", popped);
return popped;
}
char* peek(struct StackNode* root)
{
if (isEmpty(root))
return NULL;
return root->data;
}
char buffer[64];
char *ca = &buffer[0];
size_t size = 64;
int bufferIndex;
int first = 0;
int isWhiteSpace (char c) {
if ((c == ' ') || (c == '\t') || (c == '\r')) {
return 1;
}
else {
return 0;
}
}
char* getToken() {
char* token = malloc(64);
int i = 0;
while ((isWhiteSpace(buffer[bufferIndex])) && bufferIndex < strlen(buffer)-1) {
bufferIndex++;
}
while (bufferIndex < strlen(buffer)-1) {
int num = isWhiteSpace(buffer[bufferIndex]);
if (num == 0) {
token[i] = buffer[bufferIndex];
i++;
bufferIndex++;
//printf("%s\n", token);
}
else {
bufferIndex++;
break;
}
}
token[i] = '\0';
first++;
return token;
}
int main() {
while (1) {
char* token = "test";
char* postFix = "test";
char* hold = malloc(64);
postFix = malloc(64);
int total = 0;
int pres1 = 0;
int pres2 = 0;
struct StackNode* root = NULL;
printf("Enter line: ");
getline(&ca,&size,stdin);
bufferIndex = 0;
if ((strcmp(token, "quit") == 0)) {
token = getToken();
if (strcmp(token, "") == 0) {
break;
}
else {
printf("Too many arguments. Try again.\n");
}
}
else {
while (strcmp(token, "") != 0) {
token = getToken();
//printf("%s\n", token);
//printf("Top of stack: %s\n", peek(root));
if (isdigit(*token) == 1) {
strcat(postFix, token);
strcat(postFix, " ");
printf("%s\n", postFix);
}
else if (peek(root) == NULL) {
push(&root, token);
}
else {
printf("Peek: %s\n", peek(root));
if (strcmp(token, "*") == 0) {
pres1 = 2;
}
else if (strcmp(token, "/") == 0) {
pres1 = 2;
}
else if (strcmp(token, "-") == 0) {
pres1 = 1;
}
else if (strcmp(token, "+") == 0) {
pres1 = 1;
}
else {
pres1 = 0;
}
if (strcmp(peek(root), "*") == 0) {
pres2 = 2;
}
else if (strcmp(peek(root), "/") == 0) {
pres2 = 2;
}
else if (strcmp(peek(root), "-") == 0) {
pres2 = 1;
}
else if (strcmp(peek(root), "+") == 0) {
pres2 = 1;
}
while((peek(root) != NULL) && (pres2 > pres1)) {
strcat(postFix, peek(root));
strcat(postFix, " ");
pop(&root);
printf("Postfix: %s\n", postFix);
}
push(&root, token);
}
}
do {
//printf("Peek in DO/WHILE: %s\n", peek(root));
strcat(postFix, peek(root));
strcat(postFix, " ");
pop(&root);
} while ((peek(root) != NULL));
printf("Postfix: %s\n", postFix);
//ca = NULL;
token = "1";
bufferIndex = 0;
for (int i = 0; i < strlen(postFix) + 1; i++) {
buffer[i] = postFix[i];
}
//size = strlen(postFix)+1;
//printf("TOKEN: %s\n", token);
while (strcmp(token, "") != 0) {
token = getToken();
if (isdigit(*token) == 1) {
//printf("--Token: %s\n", token);
push(&root, token);
}
else {
int operand1;
//operand1 = malloc(64);
int operand2;
//total = malloc(64);
printf("Peek: %s\n", peek(root));
operand2 = atoi(peek(root));
pop(&root);
printf("Operand2: %d\n", operand2);
if (strcmp(token, "") != 0) {
printf("Peek: %s\n", peek(root));
operand1 = atoi(peek(root));
pop(&root);
printf("Operand1: %d\n", operand1);
printf("Token: %s\n", token);
if (strcmp(token, "+") == 0) {
total = operand1 + operand2;
}
else if (strcmp(token, "/") == 0) {
total = operand1 / operand2;
}
else if (strcmp(token, "-") == 0) {
total = operand1 - operand2;
}
else if (strcmp(token, "*") == 0) {
total = operand1 * operand2;
}
sprintf(hold,"%d",total);
//printf("Peek: %s\n", peek(root));
push(&root, hold);
//pop(&root);
printf("Total: %d\n", total);
}
else {
//printf("Peek: %s\n", peek(root));
break;
}
}
}
}
printf("Total: %d\n", total);
}
return 0;
}
I am supposed to/am using this as a reference for the assignment: http://condor.depaul.edu/ichu/csc415/notes/notes9/Infix.htm
isdigit() should only be tested for zeroness
Instead of:
if (isdigit(*token) == 1) {
use:
if (isdigit((unsigned char)*token)) {
pointers make it easy to overwrite memory used elsewhere
The code does:
char* hold = malloc(64);
and then later on loops doing:
while (/* ... */) {
// ...
sprintf(hold,"%d",total);
push(&root, hold);
// ...
}
This causes all the values stored on the stack to share the same storage and to be overwritten whenever hold is changed.
The allocation must happen on every use:
char *hold;
// ...
while (/* ... */) {
// ...
hold = malloc(64);
sprintf(hold,"%d",total);
push(&root, hold);
// ...
}
I'm trying to make when I put some numbers in scan, and if there's mine(*), print boom and if there's no mine, print the number of mines near to it. I can't find a problem with the code, but there's an error. Please verify it if you find the problem.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
int main (void)
{
char minefield [N][N];
int i, j;
int k;
int x, y;
int count;
int mine_number;
count = 0;
mine_number = N*N/10;
srand((long)time(NULL));
for (k=1; 0< k < mine_number; k=k+1) {
i = rand() % N;
j = rand() % N;
minefield [i][j] = '*';
}
for (i=0; i < N; i=i+1) {
for (j=0; j < N; j=j+1) {
count = 0;
if (minefield[i][j] != '*') {
if (i == 0) {
if (j == 0) {
if (minefield [i][j+1] == '*') {
count = count + 1;
}
if (minefield [i+1][j+1] == '*') {
count = count + 1;
}
if (minefield [i+1][j] == '*') {
count = count + 1;
}
}
else if (j == N-1) {
if (minefield [i+1][j] == '*') {
count = count + 1;
}
if (minefield [i+1][j-1] == '*') {
count = count + 1;
}
if (minefield [i][j-1] == '*') {
count = count + 1;
}
}
else {
if (minefield [i][j+1] == '*') {
count = count + 1;
}
if (minefield [i+1][j+1] == '*') {
count = count + 1;
}
if (minefield [i+1][j] == '*') {
count = count + 1;
}
if (minefield [i+1][j-1] == '*') {
count = count + 1;
}
if (minefield [i][j-1] == '*') {
count = count + 1;
}
}
}
else if (i == N-1) {
if (j == 0) {
if (minefield [i-1][j] == '*') {
count = count + 1;
}
if (minefield [i-1][j+1] == '*') {
count = count + 1;
}
if (minefield [i][j+1] == '*') {
count = count + 1;
}
}
else if (j == N-1) {
if (minefield [i-1][j] == '*') {
count = count + 1;
}
if (minefield [i-1][j-1] == '*') {
count = count + 1;
}
if (minefield [i][j-1] == '*') {
count = count + 1;
}
}
else {
if (minefield [i][j+1] == '*') {
count = count + 1;
}
if (minefield [i-1][j+1] == '*') {
count = count + 1;
}
if (minefield [i-1][j] == '*') {
count = count + 1;
}
if (minefield [i-1][j-1] == '*') {
count = count + 1;
}
if (minefield [i][j-1] == '*') {
count = count + 1;
}
}
}
else {
if (j == 0) {
if (minefield [i-1][j] == '*') {
count = count + 1;
}
if (minefield [i-1][j+1] == '*') {
count = count + 1;
}
if (minefield [i][j+1] == '*') {
count = count + 1;
}
if (minefield [i+1][j+1] == '*') {
count = count + 1;
}
if (minefield [i+1][j] == '*') {
count = count + 1;
}
}
else if (j == N-1) {
if (minefield [i-1][j] == '*') {
count = count + 1;
}
if (minefield [i-1][j-1] == '*') {
count = count + 1;
}
if (minefield [i][j-1] == '*') {
count = count + 1;
}
if (minefield [i+1][j-1] == '*') {
count = count + 1;
}
if (minefield [i+1][j] == '*') {
count = count + 1;
}
}
else {
if (minefield [i-1][j-1] == '*') {
count = count + 1;
}
if (minefield [i-1][j] == '*') {
count = count + 1;
}
if (minefield [i-1][j+1] == '*') {
count = count + 1;
}
if (minefield [i][j+1] == '*') {
count = count + 1;
}
if (minefield [i][j-1] == '*') {
count = count + 1;
}
if (minefield [i+1][j-1] == '*') {
count = count + 1;
}
if (minefield [i+1][j] == '*') {
count = count + 1;
}
if (minefield [i+1][j+1] == '*') {
count = count + 1;
}
}
}
}
}
}
scanf("%d %d", &x, &y);
if (minefield[x][y] = '*') {
printf("boom");
}
else {
printf("%d", count);
}
return 0;
}
Your basic problem is that you are counting before you read the input, i.e. before you know what x and y is. In other words, currently you are counting "something" on the whole minefield which isn't what you want.
So the first thing to do is to read x and y before counting.
Further it seems to me that your big if statement is hard to read. You could reorganize it like:
if (scanf("%d %d", &x, &y) != 2 || x < 0 || x >= N || y < 0 || y >= N)
{
// Illegal input
exit(1);
}
if (minefield[x][y] == '*') {
printf("boom");
}
else {
count = 0;
if (x-1 >= 0 && y-1 >= 0) count += (minefield[x-1][y-1] == '*');
if (x-1 >= 0) count += (minefield[x-1][y] == '*');
....
.... Add code to cover all 8 combinations (i.e. add the 5 missing combinations)
....
if (x+1 < N && y+1 < N) count += (minefield[x+1][y+1] == '*');
printf("%d", count);
}
I have to read a file in the console in C, the file is a CSV file. My code is the following :
printf("Ajouter un site internet \n");
printf("------------------------------------------\n");
FILE * curseur = fopen("listess.csv", "a");
SITES * pSites = calloc(100000, sizeof(SITES));
int i = 0;
int iSites = 0;
int champSites = 0;
char temp[1000];
if (curseur != NULL) {
char c = fgetc(curseur);
while (c != EOF) {
printf("%s", (pSites + iSites)->url);
if (c != '\n' && c != ';') {
temp[i] = c;
i++;
}
else if (c == ';') {
temp[i] = '\0';
if (champSites == 0) {
strcpy((pSites + iSites)->Commune, temp);
champSites++;
i = 0;
}
else if (champSites == 1) {
strcpy((pSites + iSites)->Insee, temp);
champSites++;
i = 0;
}
else if (champSites == 2) {
strcpy((pSites + iSites)->url, temp);
champSites++;
i = 0;
}
else if (champSites == 3) {
strcpy((pSites + iSites)->Population, temp);
champSites++;
i = 0;
}
else if (champSites == 4) {
strcpy((pSites + iSites)->https, temp);
champSites++;
i = 0;
}
else if (champSites == 5) {
strcpy((pSites + iSites)->Serveur, temp);
champSites++;
i = 0;
}
else if (champSites == 6) {
strcpy((pSites + iSites)->Version, temp);
champSites++;
i = 0;
}
else if (champSites == 7) {
strcpy((pSites + iSites)->Application, temp);
champSites++;
i = 0;
}
else if (champSites == 8) {
strcpy((pSites + iSites)->VersionApplication, temp);
champSites++;
i = 0;
}
else if (champSites == 9) {
strcpy((pSites + iSites)->Langage, temp);
champSites++;
i = 0;
}
else if (champSites == 10) {
strcpy((pSites + iSites)->VersionLangage, temp);
champSites++;
i = 0;
}
else if (champSites == 11) {
strcpy((pSites + iSites)->Latitude, temp);
champSites++;
i = 0;
}
else if (champSites == 12) {
strcpy((pSites + iSites)->Longitude, temp);
champSites++;
i = 0;
}
}
else {
iSites++;
}
c = fgetc(curseur);
}
system("pause");
fclose(curseur);
}
But I do have any result in the console except the two first lines.
The file is composed of 13 columns that I declared in a .h file.
The 5 first lines of the csv:
Commune;Code Insee;url;Population;https;Serveur;Version du serveur;Application;Version de l'application;Langage;Version du langage;Latitude;Longitude
Argentat;19010;argentat.fr;3042;non;SiteW;2;Inconnue;Inconnue;php;5.3.29;45.100801186828598;1.934640270901890
Canenx-et-Réaut;40064;mairie-info.com;175;non;SiteW;2;Inconnue;Inconnue;php;5.3.29;43.999060134922502;-0.464769980981436
Chaussan;69051;chaussan.fr;972;non;SiteW;2;Inconnue;Inconnue;Inconnue;Inconnue;45.637283899086498;4.634069843807340
Étrez;1154;etrez.fr;803;non;SiteW;2;Inconnue;Inconnue;Inconnue;Inconnue;46.338283686023097;5.192873875680920
Gray ;70279;ville-gray.fr;6016;non;SiteW;2;Inconnue;Inconnue;php;5.2.10;47.432262030641297;5.610925314619960
Your code is overly complicated. Throw it away and base your new code on this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
// declare and initialize your pSites stuff here
....
//
if (curseur == NULL)
{
printf("Can't open file\n");
return 1;
}
int linenumber = 1;
char buffer[1000];
while (fgets(buffer, sizeof buffer, curseur))
{
char *token = strtok(buffer, ";");
printf("Line %d\n", linenumber++);
int column = 0;
while (token != NULL)
{
printf("%2d %s\n", column, token);
switch (column)
{
case 0:
strcpy((pSites + iSites)->Commune, token);
break;
case 1:
strcpy((pSites + iSites)->Insee, token);
break;
case 2:
.... etc.
}
token = strtok(NULL, ";");
column++;
}
iSites++;
}
fclose(curseur);
}
BTW: instead of writing
(pSites + iSites)->Commune
you should write the more readable variant:
pSites[iSites]->Commune
This:
if (champSites == 0) {
strcpy((pSites + iSites)->Commune, temp);
champSites++;
i = 0;
}
else if (champSites == 0) {
strcpy((pSites + iSites)->Insee, temp);
champSites++;
i = 0;
}
makes no sense, note that both conditions are else if(champSites == 0) which will clearly mean that most of the code is dead (won't ever execute).
Should perhaps be if 0 ... else if 1 ... else if 2 and so on.
I designed this NFA - where I input a string, and the output is Accepted if this NFA accept it else Not accepted.
My code is here -
#include <stdio.h>
#include <stdlib.h>
int accepted = 1;
struct node
{
char first, second;
struct node *left, *right;
};
int main()
{
struct node *stage, *start, *temp;
char A[50000], data;
printf("String: ");
gets(A);
int i;
for(i=0; i<strlen(A); i++)
{
if(i==0)
{
stage=(struct node*)malloc(sizeof(struct node));
if(A[i] == '0')
{
stage->first = 'B';
stage->second = 'A';
}
else if(A[i] == '1')
{
stage->first = 'A';
stage->second = '\0';
}
stage->left = '\0';
start = stage;
temp = stage;
stage->right = '\0';
}
else
{
stage=(struct node*)malloc(sizeof(struct node));
temp->right = stage;
stage->left = temp;
if(A[i] == '0')
{
if(temp->first = 'A')
{
stage->first = 'B';
stage->second = 'A';
}
else if(temp->first = 'B')
{
stage->first = '\0';
stage->second = '\0';
}
else if(temp->first = 'C')
{
stage->first = '\0';
stage->second = '\0';
}
else if(temp->first = '\0')
{
while(1)
{
stage = stage->left;
temp = stage->left;
stage->right = '\0';
i--;
if(i == 0)
{
accepted = 0;
break;
}
if(stage->second != '\0')
{
stage->first = stage->second;
stage->second = '\0';
break;
}
}
}
}
else if(A[i] == '1')
{
if(temp->first = 'A')
{
stage->first = 'A';
stage->second = '\0';
}
else if(temp->first = 'B')
{
stage->first = 'C';
stage->second = '\0';
}
else if(temp->first = 'C')
{
stage->first = 'C';
stage->second = '\0';
}
else if(temp->first = '\0')
{
while(1)
{
stage = stage->left;
temp = stage->left;
stage->right = '\0';
i--;
if(i == 0)
{
accepted = 0;
break;
}
if(stage->second != '\0')
{
stage->first = stage->second;
stage->second = '\0';
break;
}
}
}
}
temp = stage;
stage->right = '\0';
}
}
temp = start;
printf("\n");
while(1)
{
printf("%c => ", temp->first);
temp = temp->right;
if(temp->right == '\0')
{
data = temp->first;
break;
}
}
if(accepted && data == 'C') printf("\n\nAccepted.\n");
else printf("\n\nNot accepted.\n");
return 0;
}
Please help me to find, what's wrong there.