Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    May 2008
    Messaggi
    475

    [C++] Modificare una string

    Ciao a tutti,

    ho un piccolo problema con le string.
    Il mio programma legge da tastiera un'espressione matematica. L'idea più semplice che mi è venuta è stata:

    codice:
    string token;
    
    cin >> token;
    while (token.compare(terminator) != 0)
    {
        outputVector.push_back(token);
        cin >> token;
    }
    Il che funziona piuttosto bene. Il problema è che se io scrivo "(3 + 4)", con questo metodo viene diviso in 3 string:
    codice:
    (3
    +
    4)
    Il che naturalmente non è bello...

    In pratica dovrei prendere una string del tipo (xxx) e riuscire ad aggiungere al vettore la parentesi (se c'è), la parte centrale, e la parentesi finale (se c'è).
    In realtà ovviamente ce ne sarà sempre e solo una, però così può gestire entrambi i casi.

    Ho provato a scrivere un pezzettino di codice che avrebbe anche funzionato in teoria, ma il tutto si è infranto miseramente contro il fatto che string::c_str() ritorna un CONST char*, che quindi non posso modificare.

    In ogni caso, sento che questa soluzione non è elegante, ci deve essere qualcosa di meglio... (parlo anche proprio della fase di lettura).

    Avete qualche suggerimento?
    "Let him who has understanding reckon the number of the beast, for it is a human number.
    Its number is rw-rw-rw-."

  2. #2
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Se il problema sono gli spazi puoi risolvere con:
    codice:
    string token;
    
    getline(cin,token);
    while (token.compare(terminator) != 0)
    {
        outputVector.push_back(token);
        getline(cin,token);
    }
    This code and information is provided "as is" without warranty of any kind, either expressed
    or implied, including but not limited to the implied warranties of merchantability and/or
    fitness for a particular purpose.

  3. #3
    Utente di HTML.it
    Registrato dal
    May 2008
    Messaggi
    475
    No, il problema è che devo vedere se una string inizia o finisce con una parentesi, chiusa o aperta, e separarla in 2 string di conseguenza.

    Esempio, "(35" deve diventare "(" e "35", mentre
    "121)" deve diventare "121" e ")".
    "Let him who has understanding reckon the number of the beast, for it is a human number.
    Its number is rw-rw-rw-."

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.