2014-04-11 2 views
1

Проблема:istringstream вопрос

У меня есть текстовый файл с линиями информации в нем, как необходимость ниже в разделе «текстовый файл». Я пытаюсь сопоставить элементы, чтобы закончить свое задание. При их сопоставлении я использую istringstream. Моя проблема возникает в том, чтобы заставить ее работать, когда в элементе есть несколько слов, которые я хочу сохранить в одной строке. Например, «Unsweetened Applesauce», я хочу, чтобы это была одна строка (item.setNewItem). Любая помощь действительно была бы признательна, и поскольку я являюсь нынешним учеником, любой потакание ради меня будет действительно оценен. =)

TXT файл:

1 чашка сахара | 1 чашка несладкого яблочного соуса | калорийность

Код:

void mapList(ifstream &foodReplace, map<string, Substitutions> &subs) 
{ 
    string line; 
    while (getline (foodReplace, line)); 
    { 
     Substitutions item; 
     istringstream readLine(line); 

     readLine << item.setOldAmount 
       << item.setOldMeasurement 
       << item.setOldItem 
       << item.setNewAmount 
       << item.setNewMeasurement 
       << item.setNewItem; 

     subs.insert(pair<string, Substitutions>(item.getOldItem, item)); 
    } 

} 
+0

Измените свой ввод, чтобы использовать разделители между словами, чтобы вы могли разбить строку между логическими частями. Что-то вроде 'food Unsweetened Applesauce endFood' Это плохой человек XML :-) – AndyG

+0

И XML - это бедный человек csv, как все знают. – Deduplicator

ответ

0

Вы можете просто поставить третий параметр GetLine, чтобы указать разделитель:

http://www.cplusplus.com/reference/string/string/getline/

И тогда вы можете прочитать первое и второе поля в '', а третье поле - '|'.

вызов будет гласить:

void mapList(ifstream &foodReplace, map<string, Substitutions> &subs) 
{ 
    string line; 
    while (getline (foodReplace, line)); 
    { 
     Substitutions item; 
     istringstream readLine(line); 

     getline(readLine, item.setOldAmount, ' '); //you may need to read this in to a temp string if setOldAmount is an int 
     getline(readLine, item.setOldMeasurement, ' '); 
     getline(readLine, item.setOldItem, '|'); 

     getline(readLine, item.setNewAmount, ' '); //you may need to read this in to a temp string if setNewAmount is an int 
     getline(readLine, item.setNewMeasurement, ' '); 
     getline(readLine, item.setNewItem, '|'); 

     subs.insert(pair<string, Substitutions>(item.getOldItem, item)); 
    } 

} 
0

Я действительно ценят помощь каждого, она поможет мне попасть туда, куда мне было нужно, даже если я не использовать один и тот же код, ниже решение, которое я пошли, снова, спасибо всем. =)

//function to populate map and update object info 
void mapList(fstream &foodReplace, map<string, Substitutions> &subs) 
{ 
    string line; 
    while (getline (foodReplace, line)) //gets the line and saves it to line 
    { 
     Substitutions item; 
     istringstream readLine(line); //reads it into readLine 

     //declaring variables 
     double amount; 
     string unit; 
     string ingredient; 
     string benefit; 

     //gets old ingredient and saves in object 
     getIngredient(readLine, amount, unit, ingredient); 
     item.setOldAmount(amount); 
     item.setOldMeasurement(unit); 
     item.setOldItem(ingredient); 

     //gets new ingredient and saves to object 
     getIngredient(readLine, amount, unit, ingredient); 
     item.setNewAmount(amount); 
     item.setNewMeasurement(unit); 
     item.setNewItem(ingredient); 

     //reads in last piece and saves in object 
     readLine >> benefit; 
     item.setBenefit(benefit); 

     //inserts object into map 
     subs.insert(pair<string, Substitutions>(item.getOldItem(), item)); 
    } 
} 

//function to extract amount-units-ingredient 
void getIngredient(istringstream &stream, double &amount, string &unit, string &ingredient) 
{ 
    //resetting variables 
    amount = 0; 
    unit = ""; 
    ingredient = ""; 
    string temp; 

    //setting variables 
    stream >> amount; 
    stream >> unit; 
    stream >> temp; 

    //read until delimiter is hit 
    while (temp != "|") 
    { 
     ingredient += temp + " "; 
     stream >> temp; 
    } 

    //removes the space at the end of the ingredient 
    ingredient = ingredient.substr(0, ingredient.length() - 1); 
} 
Смежные вопросы